text
stringlengths
2
6.14k
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { createStructuredSelector } from 'reselect'; import { isPristine, change } from 'redux-form'; import RelaisForm from 'containers/AdminRelais/components/RelaisForm'; import { makeSelectPending } from 'containers/App/selectors'; import { saveRelais } from 'containers/AdminRelais/actions'; const isProfilePristine = () => state => isPristine('profile')(state); class InfosRelais extends Component { // eslint-disable-line static propTypes = { changeValue: PropTypes.func.isRequired, relais: PropTypes.object.isRequired, pristine: PropTypes.bool.isRequired, pending: PropTypes.bool.isRequired, save: PropTypes.func.isRequired, }; handleSubmit = values => { this.props.save(values); }; render() { const { relais, pending, pristine, changeValue } = this.props; return ( <div className="row"> <RelaisForm changePresentation={val => changeValue('relais', 'presentation', val)} initialValues={relais} onSubmit={this.handleSubmit} pending={pending} pristine={pristine} /> </div> ); } } const mapStateToProps = createStructuredSelector({ pending: makeSelectPending(), pristine: isProfilePristine(), }); const mapDispatchToProps = dispatch => bindActionCreators( { changeValue: change, save: saveRelais, }, dispatch ); export default connect(mapStateToProps, mapDispatchToProps)(InfosRelais);
const { parse: parseSvg, Tree } = require('postsvg'); class Image { /** * @param {string|PostSvgTree} content * @param {string} path */ constructor(path, content) { const parts = path.split('?'); this.path = parts[0]; this.query = parts[1] ? `?${parts[1]}` : ''; this._tree = content instanceof Tree ? content : parseSvg(content.toString()); } /** * @return {Array<number>|undefined} */ get viewBox() { const { width, height } = this; const { viewBox } = this._tree.root.attrs || {}; let result; if (viewBox) { result = viewBox.split(' ').map(parseFloat); } else if (width && height) { result = [0, 0, width, height]; } return result; } /** * @return {number|undefined} */ get width() { const root = this._tree.root; const { width, viewBox } = root.attrs || {}; return width || viewBox ? parseFloat(width || viewBox.split(' ')[2]) : undefined; } /** * @return {number|undefined} */ get height() { const { height, viewBox } = this._tree.root.attrs || {}; return height || viewBox ? parseFloat(height || viewBox.split(' ')[3]) : undefined; // eslint-disable-line no-magic-numbers } /** * @return {string} */ get content() { return this.toString(); } /** * @return {PostSvgTree} */ get tree() { return this._tree.clone(); } /** * @return {string} */ toString() { return this._tree.toString(); } } module.exports = Image;
// For browsers var testSuites = [ 'specs/util', 'specs/config', 'specs/module', 'specs/package', 'specs/extensible', 'specs/extensible/seajs-debug', 'specs/extensible/seajs-flush', 'specs/extensible/seajs-style', 'specs/misc/bootstrap', 'specs/misc/callback-order', 'specs/misc/ie-cache', 'specs/misc/load-perf', 'specs/misc/on-error', 'specs/misc/utf8-in-gbk', 'specs/misc/x-ua-compatible', 'research/derive-uri' ] // For seajs in node if (typeof define === 'function') { define([ 'specs/config', 'specs/module', 'specs/package', 'specs/node' ]) }
jest.dontMock('../pagination-reducer'); jest.dontMock('../middleware'); const { LAGER_RESET, LAGER_REQUEST, LAGER_FAILURE, LAGER_SUCCESS, LAGER_ACTION, } = require('../middleware'); const pagination = require('../pagination-reducer').default; const removePageParam = require('../pagination-reducer').removePageParam; describe('removePageParam', () => { it('should remove page query param', () => { expect(removePageParam('me/resource?page=1')).toEqual('me/resource'); }); }); describe('ResultReducer', () => { let state = {}; const successWith = data => ({ [LAGER_ACTION]: LAGER_SUCCESS, ...data, }); const requestWith = data => ({ [LAGER_ACTION]: LAGER_REQUEST, ...data, }); const errorWith = data => ({ [LAGER_ACTION]: LAGER_FAILURE, ...data, }); const reset = identifier => ({ [LAGER_ACTION]: LAGER_RESET, identifier, }); const identifier = 'resource/1'; it('should be loading on request', () => { const oneEntityAction = requestWith({ input: `${identifier}?page=1`, identifier: `${identifier}?page=1`, }); state = pagination(state, oneEntityAction); expect(state[identifier].loading).toEqual(true); expect(state[identifier].pages[0].loading).toEqual(true); }); it('should be failed on failed request', () => { const oneEntityAction = errorWith({ input: `${identifier}?page=1`, identifier: `${identifier}?page=1`, }); state = pagination(state, oneEntityAction); expect(state[identifier].loading).toEqual(false); expect(state[identifier].error).toEqual(true); expect(state[identifier].pages[0].loading).toEqual(false); }); it('should succeed on succes request', () => { const oneEntityAction = successWith({ input: `${identifier}?page=1`, identifier: `${identifier}?page=1`, response: { result: { users: [ { id: 4, kalle: 2 }, { id: 3, kalle: 2 }, { id: 2, kalle: 2 }, ], perPage: 3, totalEntries: 10, currentPage: 1, }, }, schemaKeys: ['users'], }); state = pagination(state, oneEntityAction); expect(state[identifier].loading).toEqual(false); expect(state[identifier].pages[0].loading).toEqual(false); expect(state[identifier].error).toEqual(false); expect(state[identifier].pages[0].users.length).toEqual(3); }); it('should be loading on second page request', () => { const oneEntityAction = requestWith({ input: `${identifier}?page=2`, identifier: `${identifier}?page=2`, }); state = pagination(state, oneEntityAction); expect(state[identifier].pages[1].loading).toEqual(true); }); it('should succeed on second page succes request', () => { const oneEntityAction = successWith({ input: `${identifier}?page=2`, identifier: `${identifier}?page=2`, response: { result: { users: [ { id: 14, kalle: 2 }, { id: 13, kalle: 2 }, { id: 12, kalle: 2 }, ], perPage: 3, totalEntries: 10, currentPage: 2, }, }, schemaKeys: ['users'], }); state = pagination(state, oneEntityAction); expect(state[identifier].loading).toEqual(false); expect(state[identifier].error).toEqual(false); expect(state[identifier].pages[1].loading).toEqual(false); expect(state[identifier].pages[1].users.length).toEqual(3); }); it('should reset it all', () => { state = pagination(state, reset(identifier)); expect(state[identifier]).toEqual(null); }); });
import { asMoney } from '@/transforms/currency' import { date } from '@/transforms/date' import _ from 'lodash' const filters = { asMoney, date } export const register = Vue => { _.forEach(filters, (filter, name) => { Vue.filter(name, filter) }) }
var searchData= [ ['hydrographic_5fnetwork_2ecpp',['hydrographic_network.cpp',['../a00033.html',1,'']]], ['hydrographic_5fnetwork_2eh',['hydrographic_network.h',['../a00034.html',1,'']]], ['hydrographic_5fnetwork_5fsave_5ffiles_5fprefix',['HYDROGRAPHIC_NETWORK_SAVE_FILES_PREFIX',['../a00036.html#a7892be5281d6d9f76170746d3e924023',1,'main.cpp']]], ['hydrographicnetwork',['HydrographicNetwork',['../a00011.html',1,'HydrographicNetwork'],['../a00011.html#a8fe7535f39706caa3409502bb6f2f399',1,'HydrographicNetwork::HydrographicNetwork()']]], ['hydrographicnetworkmenu',['HydrographicNetworkMenu',['../a00036.html#aafcac47ce1c36aa1e9a3f8b4b7211079',1,'main.cpp']]] ];
'use strict'; /*global eventsApp*/ eventsApp.filter('durations', function() { return function(duration) { switch(duration) { case 1: return '30 mins'; case 2: return '1 Hour'; case 3: return 'Half Day'; case 4: return 'Full Day'; default: return "Unknown duration"; } }; });
var r = require('rethinkdb'); var BACKLOG_LIMIT = 100; function socketAppCtor(cfg, pool) { return function socketApp(socket) { var createMessage = require('./controllers/messages/create.js')(pool); // just listen for changes in sidebar filter status - // report every new message in active filters var filters; function reportError(err){ socket.write({ type: 'error', err: err }); } function haveMessage(message){ socket.write({ type: 'haveMessage', message: message }); } var adHocFilterCursor = null; function closeAdHocFilterCursor() { if (adHocFilterCursor) { adHocFilterCursor.close(); adHocFilterCursor = null; } } function setAdHocFilterCursor(cursor) { return adHocFilterCursor = cursor; } function setAdHocFilter(filter) { closeAdHocFilterCursor(); pool.runQuery( r.table('messages').orderBy({index:r.desc('creation')}) .filter(r.row('scope').match(filter) .or(r.row('body').match(filter))) .limit(BACKLOG_LIMIT).orderBy('creation')) .then(setAdHocFilterCursor) .then(function(){ adHocFilterCursor.each(function (err, message) { if (err) return reportError(err); haveMessage(message); }, switchToChangefeed); }) .catch(reportError); function switchToChangefeed() { closeAdHocFilterCursor(); pool.runQuery(r.table('messages') .filter(r.row('scope').match(filter) .or(r.row('body').match(filter))).changes()) .then(setAdHocFilterCursor) .then(function(){ adHocFilterCursor.each(function (err, changes) { if (err) return reportError(err); haveMessage(changes.new_val); }); }) .catch(reportError); } } socket.on('data', function(data){ if (data.type == 'error') return console.error(data); else if (data.type == 'createMessage') { createMessage(data.message); } else if (data.type == 'setAdHocFilter') { setAdHocFilter(data.filter); } else { console.error('Unrecognized message type', data); } }); }} module.exports = socketAppCtor;
import test from 'ava'; import crc32 from './../../src/utils/crc32'; test('CRC32', (t) => { t.is(crc32('Hello World'), 1243066710); });
var pSlice = Array.prototype.slice; var Object_keys = typeof Object.keys === 'function' ? Object.keys : function (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; } ; var deepEqual = module.exports = function (actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (actual instanceof Date && expected instanceof Date) { return actual.getTime() === expected.getTime(); } else if (isNumberNaN(actual)) { return isNumberNaN(expected); // 7.3. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (typeof actual != 'object' && typeof expected != 'object') { return actual == expected; // 7.4. For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } } function isUndefinedOrNull(value) { return value === null || value === undefined; } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function isNumberNaN(value) { // NaN === NaN -> false return typeof value == 'number' && value !== value; } function objEquiv(a, b) { if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return deepEqual(a, b); } try { var ka = Object_keys(a), kb = Object_keys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!deepEqual(a[key], b[key])) return false; } return true; }
/** * # Attribute * * Programmatically add attributes or change attribute values. * * @module nag.attribute */ angular.module('nag.attribute', []);
import Posts from "meteor/nova:posts"; var Future = Npm.require( 'fibers/future' ); Meteor.methods({ 'sendPushNotification':function(push_username, push_message) { console.log("Test"); // Array of UserIDs where we want to send the message. var userIdsToPushNotify = [Meteor.userId()]; Push.send({ from: 'push', title: push_username, text: push_message, badge: 1, sound: 'chime', query: { userId: { $in: userIdsToPushNotify } } }); }, 'getGooglePlaces':function(place){ console.log("server method called",place); var future = new Future(); // var response = Meteor.wrapAsync(callGooglePlaces); // var responseRes = response(place) // console.log("response res",responseRes) // return responseRes; Meteor.http.get("https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+place+"&types=(cities)&language=en_US&key=AIzaSyD19U3ToWPVJpnFk7AGRT8O68qfO2sUaJ0", function(err, result) { //console.log("inside http",err,result); if (!err) { future.return(result); } else { //future.return(err); } }); // do something with the result. return future.wait(); }, onNotificationClick () { // on notification click }, 'getPostById':function(id) { return Posts.find({_id:id}).fetch(); } }); var callGooglePlaces = function(place) { Meteor.http.get("https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+place+"&types=(cities)&language=en_US&key=AIzaSyD19U3ToWPVJpnFk7AGRT8O68qfO2sUaJ0", function(err, result) { //console.log("inside http",err,result); if (!err) { return result } return err; }); }
var detect = require('../'); var jschardet = require("jschardet") var fs = require('fs'); var path = require('path'); function readFixture(csName) { return fs.readFileSync(path.join(__dirname, '..', 'tests', 'fixtures', csName.toLowerCase() + '.txt')); } var utf8 = readFixture('UTF-8'); var gb18030 = readFixture('gb18030'); suite('detection', function() { bench('UTF-8 detect', function() { detect(utf8); }); bench('UTF-8 jschardet', function() { jschardet.detect(utf8); }); bench('gb18030 detect', function() { detect(gb18030); }); bench('gb18030 jschardet', function() { jschardet.detect(gb18030); }); });
angular.module('docsApp').constant('BUILDCONFIG', { "ngVersion": "1.7.7", "version": "1.1.18", "repository": "https://github.com/angular/material", "commit": "3e0d1e5593e38c976de98d7a7804caffd92ff1d5", "date": "2019-04-05 13:16:44 -0700" });
import PropTypes from 'prop-types'; import DialogModal from './Dialog'; import ContentModal from './Content'; const SimpleFormModal = ({ modalTitleID = 'modalTitle', children, onSubmit, onClose, ...rest }) => { return ( <DialogModal modalTitleID={modalTitleID} onClose={onClose} {...rest}> <ContentModal onSubmit={onSubmit} onReset={onClose}> {children} </ContentModal> </DialogModal> ); }; SimpleFormModal.propTypes = { ...DialogModal.propTypes, modalTitleID: PropTypes.string, children: PropTypes.node.isRequired, onSubmit: PropTypes.func, onClose: PropTypes.func.isRequired, }; export default SimpleFormModal;
var browserSync = require('browser-sync'); var webpack = require('webpack'); var webpackDevMiddleware = require('webpack-dev-middleware'); var webpackHotMiddleware = require('webpack-hot-middleware'); var history = require('connect-history-api-fallback'); var paths = require('./helpers/paths'); var webpackConfig = require('./webpack.config'); var bundler = webpack(webpackConfig); browserSync({ logFileChanges: false, notify: false, server: { baseDir: paths.srcDir, middleware: [ history(), webpackDevMiddleware(bundler, { publicPath: webpackConfig.output.publicPath, hot: true, quiet: false, stats: { chunks: false, chunkModules: false, colors: true } }), webpackHotMiddleware(bundler) ] }, files: [ paths.srcDir + '/*.html', paths.srcDir + '/*.css' ] })
var domInsert = require("./dom-insert"); var complain = "MARKO_DEBUG" && require("complain"); function getRootNode(el) { var cur = el; while (cur.parentNode) cur = cur.parentNode; return cur; } function getComponentDefs(result) { var componentDefs = result.___components; if (!componentDefs) { throw Error("No component"); } return componentDefs; } function RenderResult(out) { this.out = this.___out = out; this.___components = undefined; } module.exports = RenderResult; var proto = (RenderResult.prototype = { getComponent: function () { return this.getComponents()[0]; }, getComponents: function (selector) { if (this.___components === undefined) { throw Error("Not added to DOM"); } var componentDefs = getComponentDefs(this); var components = []; componentDefs.forEach(function (componentDef) { var component = componentDef.___component; if (!selector || selector(component)) { components.push(component); } }); return components; }, afterInsert: function (host) { var out = this.___out; var componentsContext = out.___components; if (componentsContext) { this.___components = componentsContext.___initComponents(host); } else { this.___components = null; } return this; }, getNode: function (host) { return this.___out.___getNode(host); }, getOutput: function () { return this.___out.___getOutput(); }, toString: function () { return this.___out.toString(); }, document: typeof window === "object" && document }); Object.defineProperty(proto, "html", { get: function () { // eslint-disable-next-line no-constant-condition if ("MARKO_DEBUG") { complain( 'The "html" property is deprecated. Please use "toString" instead.' ); } return this.toString(); } }); Object.defineProperty(proto, "context", { get: function () { // eslint-disable-next-line no-constant-condition if ("MARKO_DEBUG") { complain( 'The "context" property is deprecated. Please use "out" instead.' ); } return this.___out; } }); // Add all of the following DOM methods to Component.prototype: // - appendTo(referenceEl) // - replace(referenceEl) // - replaceChildrenOf(referenceEl) // - insertBefore(referenceEl) // - insertAfter(referenceEl) // - prependTo(referenceEl) domInsert( proto, function getEl(renderResult, referenceEl) { return renderResult.getNode(getRootNode(referenceEl)); }, function afterInsert(renderResult, referenceEl) { return renderResult.afterInsert(getRootNode(referenceEl)); } );
/* @flow */ import test from 'test' import { compileNpm } from 'compiler' test('compiling npm packages to ES modules', async t => { const compiledCode = await compileNpm('react') t.true(compiledCode.includes('export default react')) })
/** * Created by lee on 2016/10/03. */ $(".subject a").each(DA.renderTag);
// JavaScript Olympics // I paired [by myself, with:] on this challenge. // This challenge took me [#] hours. // Warm Up // Bulk Up //pseudocode //input: array of athlete names and event //output: a string saying "name of athlete "won" event" //steps: //1. create a function called win that accepts one argument //2. create the variables (athletes) that will be given as arguments to the function //3. give each variable the name property and the event property //4. in the function, make it print out each variable name along with "won" and the event property. var Amaar = { name: "Amaar", event: "Mens Single" } var Alicia = { name: "Alicia", event: "500 Meter Dash" } var olympics = function(athletes) { athletes.forEach(function(athletes) { console.log(athletes.name + " won the " + athletes.event + "!"); })} olympics([Amaar, Alicia]); // Jumble your words // Pseudocode // Input: A string // Ouptut: Reversed string // Step 1: Convert string into individual elements // Step 2: Reverse individual elements // Step 3: Join all the elements into a string var reverseString = function(string) { console.log((string.split("")).reverse().join("").toString()) } reverseString("Hello") // 2,4,6,8 //pseudocode // input: an array of numbers // output: an array of only even numbers from the input array // steps: //1. create a function that takes in one argument //2. create conditional statement within the function that is true when each element is divisible by two. //3. if the number is divisible by two print it to the screen. var evenNumber = function(array) { array.forEach(function(eachNumber) { if(eachNumber % 2 === 0) { console.log(eachNumber); } } ) }; evenNumber([1,2,3,4,5,6]) // "We built this city" // pseudocode // input: Input a string (name), input a integer (age), input a string (sport name), input a string(famous quote) // output: One string which includes the name, sport name, and famous quote // Step 1: create a function c function Athlete(name, age, sport, quote){ this.name = name; this.age = age; this.sport = sport; this.quote = quote; }; var michaelPhelps = new Athlete("Michael Phelps", 29, "swimming", "It's medicinal I swear!") console.log(michaelPhelps.constructor === Athlete) console.log(michaelPhelps.name + " " + michaelPhelps.sport + " " + michaelPhelps.quote) // Reflection // In the reflection section of the javascript_olympics.js file, answer the following questions: // What JavaScript knowledge did you solidify in this challenge? // This challenge, in particular, taught me how to create a data type and then subsequently use it in the function that we created. We also learned how to iterate using Javascript. // What are constructor functions? // I am still a little confused about constructer functions and while my partner was able to explain to me what it does, I still don't have a complete understanding. From my understanding, a constructer functon creates a new instance of the thing that is being constructed. But I am still not sure why new and constructer are different functions. // How are constructors different from Ruby classes (in your research)? // From my research while Ruby classes already have all the variables defined, meaning all the data in the metaclass is passed to the new class, in constructers you have to define variables each and every time you call a constructer function.
'use strict'; /* global app:false */ app.directive('clock', ['$interval', function ($interval) { return { templateUrl: 'app/clock/clock.html', restrict: 'E', replace: true, link: function ($scope) { var tick = function() { $scope.clock = Date.now(); }; tick(); $interval(tick, 1000); } }; }]);
/*global yaajs*/ define(function () { var mod = yaajs.module.ctx.modules['data/define-no-deps']; if (mod.hasOwnProperty('exports')) return "module should not have exports"; return "success"; });
/** * Created by michaelfisher on 6/18/15. */ /*jslint node: true */ "use strict"; var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); var Schema = mongoose.Schema; var userSchema = new Schema({ name: String, email: { type: String, required: true, set: function (value) { return value.trim().toLowerCase(); }, validate: [ function (email) { return (email.match(/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i) !== null), 'Invalid email'; } ] }, password: String, admin: { type: Boolean, default: false }, savedItems: [{type: Schema.Types.ObjectId, ref: 'Item'}] }); /** * Hashes the password before saving to database */ userSchema.pre('save', function (next) { var user = this; if (!user.isModified('password')) return next(); bcrypt.hash(user.password, null, null, function (err, hash) { if (err) return next(err); user.password = hash; next(); }); }); /** * Compare to hashed password. * @param password * @returns {*} */ userSchema.methods.comparePassword = function (password) { var user = this; return bcrypt.compareSync(password, user.password); }; /** * List all Users */ userSchema.static({ list: function (callback) { this.find({}).sort('-_id').select('email').exec(callback); } }); module.exports = mongoose.model('User', userSchema);
// @ts-check "use strict"; const { addErrorDetailIf, filterTokens, headingStyleFor } = require("../helpers"); module.exports = { "names": [ "MD003", "heading-style", "header-style" ], "description": "Heading style", "tags": [ "headings", "headers" ], "function": function MD003(params, onError) { let style = String(params.config.style || "consistent"); filterTokens(params, "heading_open", function forToken(token) { const styleForToken = headingStyleFor(token); if (style === "consistent") { style = styleForToken; } if (styleForToken !== style) { const h12 = /h[12]/.test(token.tag); const setextWithAtx = (style === "setext_with_atx") && ((h12 && (styleForToken === "setext")) || (!h12 && (styleForToken === "atx"))); const setextWithAtxClosed = (style === "setext_with_atx_closed") && ((h12 && (styleForToken === "setext")) || (!h12 && (styleForToken === "atx_closed"))); if (!setextWithAtx && !setextWithAtxClosed) { let expected = style; if (style === "setext_with_atx") { expected = h12 ? "setext" : "atx"; } else if (style === "setext_with_atx_closed") { expected = h12 ? "setext" : "atx_closed"; } addErrorDetailIf(onError, token.lineNumber, expected, styleForToken); } } }); } };
module.exports = function testSample(superagent){ var res = superagent.get("http://darkboxjs.com").end(); res.status.should.equal(200); res = superagent.get("http://www.youappi.com/nofile").end(); res.status.should.equal(404); };
import { Component } from '@angular/core'; export default class treePlugin { static get annotations() { return [ new Component({ selector: 'tree-plugin', template: ` <span *ngIf="icon" [title]="description" [hidden]="hidden" class="icon" [ngClass]="'icon-' + icon" [class.icon-disabled]="disabled" (click)="click(node)" (dragenter)="dragenter(node)" (dragover)="dragover(node)" (dragleave)="dragleave(node)" (drop)="drop(node)" (dragstart)="dragstart(node)" (dragend)="dragend(node)" (mousedown)="mousedown(node)" (mouseenter)="mouseenter(node)" (mouseleave)="mouseleave(node)" (mousemove)="mousemove(node)" (mouseout)="mouseout(node)" (mouseover)="mouseover(node)" (mouseup)="mouseup(node)" (dblclick)="dblclick(node)"> </span> <ng-container *ngIf="node.selectable !== false"> <div *ngIf="plugin === 'checkbox'" class="tree-node-checkbox"> <div class="checkbox"> <input type="checkbox" [checked]="node.selected" [indeterminate]="node.indeterminated" (click)="selectedChange()" [attr.disabled]="node.disabled"> <label> &nbsp; </label> </div> </div> </ng-container> <span [attr.disabled]="node.disabled" *ngIf="plugin === 'sortable' || plugin === 'nestedSortable'" class="tree-node-handle" atlui-sortable-handle></span> `, inputs: ['icon', 'description', 'plugin', 'node', 'onInit', 'onChange', 'onDestroy', 'onClick', 'onDragenter', 'onDragover', 'onDragleave', 'onDrop','onDragstart', 'onDragend', 'onMousedown', 'onMouseenter', 'onMouseleave', 'onMousemove', 'onMouseout', 'onMouseover', 'onMouseup', 'onDblclick', 'selectedChange', 'change'], outputs: [] }) ]; } constructor() { this.disabled = this.hidden = false; } // function we can send in plugins on initialisation ngOnInit(){ if (this.onChange) { var self = this; this.change.subscribe({ next() { self.onChange(self.node); } }); } if (!this.onInit) { return; } this.onInit(this.node); } // function we can send in plugins on destroy ngOnDestroy(){ if (this.disabled) { return; } if (this.onChange) { this.change.unsubscribe(); } if (!this.onDestroy) { return; } this.onDestroy(this.node); } // methods we can use in plugins for disable/activate/show and hide plugins disable() { this.disabled = true; } activate() { this.disabled = false; } show() { this.hidden = false; } hide() { this.hidden = true; } // All function we can use in our plugins click(node) { if (this.disabled) { return; } if (!this.onClick) { return; } this.onClick(node); } dragenter(node) { if (this.disabled) { return; } if (!this.onDragenter) { return; } this.onDragenter(node); } dragover(node) { if (this.disabled) { return; } if (!this.onDragover) { return; } this.onDragover(node); } dragleave(node) { if (this.disabled) { return; } if (!this.onDragleave) { return; } this.onDragleave(node); } drop(node) { if (this.disabled) { return; } if (!this.onDrop) { return; } this.onDrop(node); } dragstart(node) { if (this.disabled) { return; } if (!this.onDragstart) { return; } this.onDragstart(node); } dragend(node) { if (this.disabled) { return; } if (!this.onDragend) { return; } this.onDragend(node); } mousedown(node) { if (this.disabled) { return; } if (!this.onMousedown) { return; } this.onMousedown(node); } mouseenter(node) { if (this.disabled) { return; } if (!this.onMouseenter) { return; } this.onMouseenter(node); } mouseleave(node) { if (this.disabled) { return; } if (!this.onMouseleave) { return; } this.onMouseleave(node); } mousemove(node) { if (this.disabled) { return; } if (!this.onMousemove) { return; } this.onMousemove(node); } mouseout(node) { if (this.disabled) { return; } if (!this.onMouseout) { return; } this.onMouseout(node); } mouseover(node) { if (this.disabled) { return; } if (!this.onMouseover) { return; } this.onMouseover(node); } mouseup(node) { if (this.disabled) { return; } if (!this.onMouseup) { return; } this.onMouseup(node); } dblclick(node) { if (this.disabled) { return; } if (!this.onDblclick) { return; } this.onDblclick(node); } } treePlugin.parameters = [];
{ "version": 1565824050, "fileList": [ "data.js", "c2runtime.js", "jquery-2.1.1.min.js", "offlineClient.js", "images/tilemap.png", "images/player-sheet0.png", "images/tiledbackground2.png", "images/tiledbackground3.png", "images/target-sheet0.png", "images/sprite7-sheet0.png", "images/spritefont.png", "images/particles.png", "images/tiledbackground.png", "images/sprite-sheet0.png", "images/sprite3-sheet0.png", "images/sprite4-sheet0.png", "images/sprite8-sheet0.png", "images/sprite8-sheet1.png", "images/sprite10-sheet0.png", "images/sprite10-sheet1.png", "images/bullet-sheet0.png", "images/sprite6-sheet0.png", "images/smoke-sheet0.png", "images/sprite9-sheet0.png", "images/sprite11-sheet0.png", "images/sprite12-sheet0.png", "images/sprite12-sheet1.png", "images/sprite13-sheet0.png", "images/sprite14-sheet0.png", "images/ammo-sheet0.png", "images/health-sheet0.png", "images/sprite16-sheet0.png", "images/sprite15-sheet0.png", "images/sprite2-sheet0.png", "images/sprite17-sheet0.png", "images/sprite18-sheet0.png", "images/sprite19-sheet0.png", "images/sprite19-sheet1.png", "images/sprite19-sheet2.png", "images/tiledbackground4.png", "images/spritefont3.png", "images/9patch.png", "images/9patch2.png", "images/sprite5-sheet0.png", "images/sprite5-sheet1.png", "images/sprite20-sheet0.png", "images/sprite21-sheet0.png", "images/sprite22-sheet0.png", "images/tiledbackground5.png", "images/sprite23-sheet0.png", "images/sprite24-sheet0.png", "images/sprite25-sheet0.png", "images/pimalien-sheet0.png", "media/step.m4a", "media/step.ogg", "media/land.m4a", "media/land.ogg", "media/jump.m4a", "media/jump.ogg", "media/djump.m4a", "media/djump.ogg", "media/nmyjump.m4a", "media/nmyjump.ogg", "media/nmywalk.m4a", "media/nmywalk.ogg", "media/playerhurt.m4a", "media/playerhurt.ogg", "media/battlemode.m4a", "media/battlemode.ogg", "media/fail.m4a", "media/fail.ogg", "media/shoot.m4a", "media/shoot.ogg", "media/spup.m4a", "media/spup.ogg", "media/hpad.m4a", "media/hpad.ogg", "media/rangeplus.m4a", "media/rangeplus.ogg", "media/steplus.m4a", "media/steplus.ogg", "media/djuplus.m4a", "media/djuplus.ogg", "media/nmedie.m4a", "media/nmedie.ogg", "media/coin.m4a", "media/coin.ogg", "media/atmo1.m4a", "media/atmo1.ogg", "media/infarg.m4a", "media/infarg.ogg", "media/select0.m4a", "media/select0.ogg", "media/select1.m4a", "media/select1.ogg", "media/atmo2.m4a", "media/atmo2.ogg", "media/atmo0.m4a", "media/atmo0.ogg", "icon-16.png", "icon-32.png", "icon-114.png", "icon-128.png", "icon-256.png", "loading-logo.png", "sbg0.png", "sbg1.png", "sbg2.png", "sbg3.png", "sbg4.png", "lbg0.png", "lbg1.png", "tm0.png", "tm1.png", "tm2.png", "lbg2.png", "lbg3.png", "lbg4.png", "sbg5.png", "lbg5.png", "facebook.png", "instagram.png", "patreonmark.png", "twitter.png", "youtube.png", "rawdeflate.js", "rawinflate.js", "base64-1.7.js", "GameAnalytics.js" ] }
export * from './SignupPage';
export default function preProcessFn(fn) { if (!fn) { throw new Error('[preProcessFn] You must provide a function'); } const fnName = fn.name; const returnedFn = { [fnName]: (entity, user, ...fnParams) => { if (!entity) { throw new Error(`[${fnName}] You must provide an entity`); } if (user === undefined) { throw new Error(`[${fnName}] You must provide an user or null. Got undefined`); } return fn(entity, user, ...fnParams); }, }; return returnedFn[fnName]; }
(function() { 'use strict'; angular .module('thsClient') .controller('AboutCtrl', [ '$scope', '$log', 'AboutService', 'AppService', '$state', AboutController ]); function AboutController($scope, $log, AboutService, AppService, $state) { $log.log('Hello World from the About Controller using the $log Service'); //AppService.saveState('app.about'); localStorage.setItem("state", $state.current.name); } })();
const serve = require('koa-static'); const koa = require('koa')(); const router = require('koa-router')(); function register(app){ koa.use(router.routes()) .use(router.allowedMethods()) .use(serve(app.config.paths.static)); koa.listen(app.config.server.port); console.log("server listening on " + app.config.server.port); app.koa = koa; app.router = router; } module.exports = exports; exports.register = register;
/********************************************************************************************************************* * * Icon tasks. * *********************************************************************************************************************/ const { src, dest } = require( 'gulp' ); const rename = require( 'gulp-rename' ); const svgstore = require( 'gulp-svgstore' ); const svgmin = require( 'gulp-svgmin' ); const { readdirSync, statSync } = require( 'fs' ) // core stuff const { icons: PATHS, build: OUTPUT } = require( '../paths' ); const { errorHandler, streamToPromise } = require( '../utils/utils' ); const processDirectory = sDir => src( `${PATHS.base}/${sDir}/**/*.svg` ) .pipe( errorHandler() ) .pipe( rename({ prefix: 'icon-' })) .pipe( svgstore() ) .pipe( svgmin({ plugins: [ { removeDoctype: true }, { cleanupIDs: false }, { removeStyleElement: true }, { removeTitle: true }, { removeAttrs: { attrs: [ 'style', 'stroke.*', 'class' ]}} ] })) .pipe( rename( `icons-${sDir}.svg` )) .pipe( dest( OUTPUT )); /** * Actual build task. * * @return {Stream} a gulp stream */ const icons = () => Promise.all( readdirSync( PATHS.base ) .filter( sF => statSync( `${PATHS.base}/${sF}`).isDirectory() ) .map( processDirectory ) .map( streamToPromise ) ); /** Expose things */ module.exports = { init: [{ priority: 5, fn: icons }], watch: { files: PATHS.watch, tasks: [ icons ] }, build: [{ priority: 5, fn: icons }] }
Livefyre.require([ 'streamhub-sdk/collection', 'streamhub-sdk/content/views/content-list-view', 'auth'], function (Collection, ListView, auth) { // auth.delegate({ // login: function (done) { // var lftoken = prompt('lftoken?'); // done(null, { // livefyre: lftoken // }); // } // }); auth.delegate(auth.createDelegate('https://www.livefyre.com')); var opts = { "network": "livefyre.com", "siteId": "313878", "articleId": "1", "environment": "livefyre.com" }; var view = window.view = new ListView({ el: document.getElementById('view'), sharer: function (content) { alert('share: '+content.body); } }); var collection = window.collection = new Collection(opts); collection.pipe(view); });
describe('The main app', function() { var page = require('./main.po'); /* * NOTE: using solutionEquation.getText() crashes the tests */ beforeEach(function() { page.navigate(); }); it('can solve a 3x3 system with a precision of 3 and complete pivoting', function() { var inputValues = [ 2.15, -0.924, -1.29, 1.22, -4.12, 2.29, 0.294, -3.56, 1.01, 0.872, -3.25, -0.972 ]; page.matrixTableInputs.each(function(element, index) { element.sendKeys(inputValues[index]); }); page.pivotingSelect.element(by.cssContainingText('option', 'complete')).click(); page.decimalTypeRadio.click(); page.precisionInput.sendKeys('3'); page.submitButton.click(); var solutionText = page.solutionEquation.getAttribute('textContent'); expect(solutionText).toMatch(/ 0\.859 /); expect(solutionText).toMatch(/ -0\.081 /); expect(solutionText).toMatch(/ 0\.541 /); }); it('can move through the matrix with the keys and submit with ctrl+enter', function() { page.matrixButtons.decrease.click(); page.getMatrixTableInput(0, 0).click(); page.getActiveElement().sendKeys('1'); page.getActiveElement().sendKeys(protractor.Key.ARROW_RIGHT); page.getActiveElement().sendKeys('1'); page.getActiveElement().sendKeys(protractor.Key.ARROW_LEFT); page.getActiveElement().sendKeys('-'); page.getActiveElement().sendKeys(protractor.Key.ARROW_RIGHT); page.getActiveElement().sendKeys(protractor.Key.TAB); page.getActiveElement().sendKeys('0'); page.getActiveElement().sendKeys(protractor.Key.ENTER); page.getActiveElement().sendKeys(protractor.Key.SPACE); page.getActiveElement().sendKeys(protractor.Key.ARROW_LEFT); page.getActiveElement().sendKeys(protractor.Key.TAB); page.getActiveElement().sendKeys('1/5'); page.getActiveElement().sendKeys(protractor.Key.SPACE); page.getActiveElement().sendKeys('1/5'); page.getActiveElement().sendKeys(protractor.Key.ARROW_UP); expect(page.solutionEquation.getAttribute('textContent')).not.toMatch('x'); page.getActiveElement().sendKeys(protractor.Key.chord(protractor.Key.CONTROL, protractor.Key.ENTER)); expect(page.solutionEquation.getAttribute('textContent')).toMatch('x'); expect(page.solutionEquation.getAttribute('textContent')).toMatch(/ 1 \\\\ 1 /); // solution is [1, 1] }); });
/** * InputField component to get user input and to add placeholder text * @param {String} * @return {String} * @author Chetan Meshram <meshram.chetan@gmail.com> */ import React from "react"; require ("../style/style.scss"); const InputField = () => { return ( <div> <label htmlFor="inputField">First Name</label> <input id="inputField" type="text" /> </div> ); }; export default InputField;
// import { fromJS } from 'immutable'; // import { makeSelectTaskFormDomain } from '../selectors'; // const selector = makeSelectTaskFormDomain(); describe('makeSelectTaskFormDomain', () => { it('Expect to have unit tests specified', () => { expect(true).toEqual(false); }); });
define([ '../../moduleDef', 'angular', 'text!./templates.tpl.html', '../page' ], function (module, angular, template) { module.config(['$stateProvider', function($stateProvider) { $stateProvider.state({ name: 'page.project.templates', abstract: true, views: { '': { template: template, controller: 'reportTemplatesController' } }, resolve: { tabs: function() { return []; /*will be filled in child states*/ } //overriding resolve in custom data not working, only combination with resolve //in parent state plus onEnter in child state (see taskReportTemplates) }, onExit: function($rootScope) { $rootScope.breadcrumbs.splice($rootScope.breadcrumbs.length - 1, 1); } }); }]) .controller('reportTemplatesController', ['$scope', 'apinetService', '$window', 'i18n', 'reportService', '$stateParams', 'tabs', function($scope, apinetService, $window, i18n, reportService, $stateParams, tabs) { $scope.tabs = tabs; //inheritors must add own tabs to collection var handleException = function(error) { $scope.resetValidation(); $scope.validation.generalErrors = angular.isArray(error) ? error : [error]; }; $scope.uploadOptions = { url: reportService.templateUploadUrl(), done: function(e, data) { $scope.handleResult(data.result); }, fail: function(e, data) { //if not canceled if (data.errorThrown !== 'abort') { handleException(data.result.message); } }, submit: function(e, data) { angular.extend(data.formData, {project: $stateParams.project}); } }; $scope.itemUploadOptions = function(model) { var itemOptions = angular.copy($scope.uploadOptions); angular.extend(itemOptions, { maxNumberOfFiles: 1, submit: function(e, data) { angular.extend(data.formData, {project: $stateParams.project, templateId: model.Id}); } }); return itemOptions; }; $scope.handleResult = function(response) { if (response && response.files) { response.files.map(function(file) { var idx = $scope.findIdexById(file.model.Id); if (idx < 0) { $scope.models.push(file.model); } else { angular.extend($scope.models[idx], file.model); } }); } }; $scope.findIdexById = function(templateId) { if (!templateId) { return -1; } var modelIndex = -1; angular.forEach($scope.models, function(model, index) { if (model.Id === templateId){ modelIndex = index; } }); return modelIndex; }; $scope.delete = function(model) { if (!$window.confirm(i18n.msg('core.confirm.delete.records'))) { return; } apinetService.action({ method: 'core/reporting/DeleteTemplate', project: $stateParams.project, templateId: model.Id}) .then(function() { var index = $scope.models.indexOf(model); if (index >= 0) { $scope.models.splice(index, 1); } }, handleException); }; $scope.downloadUrl = function(template) { return reportService.templateDownloadUrl(template.ProjectCode, template.Id); }; }]); });
jestExpect(n1).not.toMatch(n2);
module.exports = function (grunt) { grunt.initConfig({ 'gh-pages': { options: { base: 'server/public', }, src: ['**'], }, }); grunt.loadNpmTasks('grunt-gh-pages'); };
// This protractor scen file tests tbColumn and tbGrid components with Local Data. // It is assumed throughout the test that the data received for the main tbGrid // component at the related HTML file (tbColumn_tests.html) is static. describe('LocalData', function() { var firstDataRow, lastDataRow, i_sortIcon, filterBtn, tbColumnFilter, popoverForm, applyBtn, clearBtn, filterSelect, valueInput, dataRows, a_customerNameSorting, a_shippedCitySorting; beforeAll(function() { // Go to test browser.get('index.html'); element(by.id('testsSelector')).click(); element(by.id('tbLocalDataTest')).click(); // Go to first page if not there element(by.tagName('tb-grid-pager')) .$('li.pagination-first a') .click(); // Select '100' on tbPageSizeSelector element(by.model('$ctrl.$component.pageSize')) .$('[value="number:100"]').click(); /**********************/ // * Test variables * // /**********************/ // First showing row firstDataRow = element.all(by.repeater('row in $component.rows')).first(); // Last showing row lastDataRow = element.all(by.repeater('row in $component.rows')).last(); // Font-awesome sort icon (indicates sort-enabled and sort order) i_sortIcon = element(by.tagName('thead')) .$$('tr th').first() .$('i'); // Sort Customer Name column link a_customerNameSorting = element(by.tagName('thead')) .$$('tr th').first() .$('a'); // Sort Shipped Date column link a_shippedCitySorting = element(by.tagName('thead')) .$$('tr th').get(2) .$('a'); }); describe('Grid Local Data Sorting', function() { beforeAll(function () { // Set test variables tbColumnFilter = element(by.tagName('tb-column-filter')); filterBtn = tbColumnFilter.$('.btn-popover'); popoverForm = $('tb-column-filter form.tubular-column-filter-form'); applyBtn = popoverForm.$('tb-column-filter-buttons').$('.btn-success'); clearBtn = popoverForm.$('tb-column-filter-buttons').$('.btn-danger'); filterSelect = popoverForm.$('select'); valueInput = popoverForm.$('input:not(.ng-hide)'); dataRows = element.all(by.repeater('row in $component.rows')); }); var dataSetLowerCustomerName = 'Apple', dataSetHigherCustomerName = 'Unosquare'; beforeEach(function() { // Clear possible sortings and start with default a_shippedCitySorting.click(); i_sortIcon.getAttribute('class').then(function(sortIconClass) { if (sortIconClass.indexOf('arrow') != -1) { if (sortIconClass.indexOf('arrow-up') != -1) { a_shippedCitySorting.click(); } a_shippedCitySorting.click(); } }); }); it('should order data in ascending order when click-sorting an unsorted text column', function() { a_customerNameSorting.click(); expect(firstDataRow.$$('td').get(0).getText()).toBe(dataSetLowerCustomerName); expect(lastDataRow.$$('td').get(0).getText()).toBe(dataSetHigherCustomerName); }); it('should order data in descending order when click-sorting an ascending-sorted text column', function() { a_customerNameSorting.click(); a_customerNameSorting.click(); expect(firstDataRow.$$('td').get(0).getText()).toBe(dataSetHigherCustomerName); expect(lastDataRow.$$('td').get(0).getText()).toBe(dataSetLowerCustomerName); }); it('should correctly filter data for the "Contains" filtering option', function () { var filterOk = true; var containedString = 'pp'; // Set filter and apply it filterBtn.click(); filterSelect.$('[value="string:Contains"]').click(); valueInput.sendKeys(containedString); applyBtn.click() .then(function () { // Verify filtering dataRows.each(function (row, index) { row.$$('td').first().getText() .then(function (customer) { filterOk = filterOk && (customer.indexOf(containedString) != -1); }); }).then(function () { expect(filterOk).toBe(true); }); }); }); it('should correctly filter data for the "Contains" with ENTER key', function () { var filterOk = true; var containedString = 'pp'; // Set filter and apply it filterBtn.click(); filterSelect.$('[value="string:Contains"]').click(); valueInput.clear(); valueInput.sendKeys(containedString); valueInput.sendKeys(protractor.Key.ENTER) .then(function () { // Verify filtering dataRows.each(function (row, index) { row.$$('td').first().getText() .then(function (customer) { filterOk = filterOk && (customer.indexOf(containedString) != -1); }); }).then(function () { expect(filterOk).toBe(true); }); }); }); }); describe('Grid Local Data tbTextSearch', function () { // TODO: Nestor }); });
function getRandomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function uidGen (len) { const buf = []; const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charlen = chars.length; for (var i = 0; i < len; ++i) { buf.push(chars[getRandomInt(0, charlen - 1)]); } return buf.join(''); } module.exports.getRandomInt = getRandomInt; module.exports.uidGen = uidGen;
version https://git-lfs.github.com/spec/v1 oid sha256:1bac5506fbd038347a8a655cd3967107fa95425b5124a324ffccf12f08233f33 size 110760
version https://git-lfs.github.com/spec/v1 oid sha256:6a52dcbe60c61158795cc9f023063121c11ce862b3e8dd71150523cc8d15ced1 size 27738
'use strict'; require('./_site-nav.scss'); require('angular').module('portfolio') .component('site-nav', { template: require('./site-nav.html'), });
module.exports = { extends: ['universe/native', 'universe/web'], };
'use strict' // import { app } from 'electron' import path from 'path'; import fs from 'fs'; import mkdirp from 'mkdirp'; import Store from 'electron-store'; import pkg from '../package.json'; import { initSettings } from './lib/settings'; import Events from './lib/events'; const store = new Store(); initSettings(); if (process.env.NODE_ENV !== 'development') { global.__static = path.join(__dirname, '/static'); } global.baseCloneDir = store.get('baseCloneDir'); global.dbDir = store.get('dbDir'); global.displayName = pkg.displayName; if (!fs.existsSync(global.baseCloneDir)) { mkdirp(global.baseCloneDir); } Events().makeSingleInstance();
version https://git-lfs.github.com/spec/v1 oid sha256:13a22071aa67958c374a6ed05331e607a0df24ac19d286d59bc4efd49795ecd1 size 3540
import React from 'react'; import { LinkContainer } from 'react-router-bootstrap'; import { Nav, NavItem } from 'react-bootstrap'; export const PublicNavigation = () => ( <Nav pullRight> <LinkContainer to="signup"> <NavItem eventKey={1} href="/signup">Sign Up</NavItem> </LinkContainer> <LinkContainer to="login"> <NavItem eventKey={2} href="/login">Log In</NavItem> </LinkContainer> </Nav> ); export default PublicNavigation;
var Module = require("module"); var globalRequire = Module.prototype.require, comb = require("comb"); function _require(name) { if (name === "amqp") { return AmqpStub(); } else { return globalRequire.apply(this, arguments); } } function Stub(proto) { var stats = {}; function addCall(name, cb) { return function () { if (name in stats) { stats[name].push(comb(arguments).toArray()); } else { stats[name] = [comb(arguments).toArray()]; } return cb.apply(this, arguments); } } for (var key in proto) { proto[key] = addCall(key, proto[key]); } return comb.merge({ reset: function reset() { stats = {}; }, calledWith: function (name, args) { return stats[name].some(function (called) { return JSON.stringify(called) === JSON.stringify(args); }); }, getCallCount: function (name) { return (stats[name] || []).length; } }, proto); } var queueStub; var QueueStub = function (name) { if (!queueStub) { queueStub = Stub({ bind: function () { return 1; }, subscribe: function () { }, shift: function () { } }); } return queueStub; }; var exchangeStub; var ExchangeStub = function (name) { if (!exchangeStub) { exchangeStub = Stub({ publish: function () { }, destroy: function () { } }) } return exchangeStub; }; var connectionStub; var ConnectionStub = function () { if (!connectionStub) { connectionStub = Stub({ on: function (event, cb) { if (event === "ready") { cb(); } }, once: function (event, cb) { if (event === "ready") { cb(); } }, removeListener: function (event, cb) { }, publish: function () { }, queue: function queue(name, opts, cb) { if ("function" === typeof opts) { cb = opts; } return cb(QueueStub(name)); }, exchange: function exchange(name, opts, cb) { if ("function" === typeof opts) { cb = opts; } return cb(ExchangeStub(name)); } }); } return connectionStub; }; var amqpStub; var AmqpStub = function () { if (!amqpStub) { amqpStub = Stub({ createConnection: function () { return ConnectionStub(); } }); } return amqpStub; }; exports.amqp = AmqpStub(); exports.connection = ConnectionStub(); exports.queue = QueueStub(); exports.exchange = ExchangeStub(); exports.reset = function () { AmqpStub().reset(); ConnectionStub().reset(); QueueStub().reset(); ExchangeStub().reset(); } Module.prototype.require = _require;
var searchData= [ ['newcreationdata',['NewCreationData',['../class_creatubbles_1_1_api_1_1_data_1_1_new_creation_data.html',1,'Creatubbles::Api::Data']]] ];
/** * * ak47 pkg * @namespace ak47 * @author 仈爪 <haibin.zhb@alipay.com> * @version 1.0.0 * * */ var fs = require('fs-extra'), path = require('path'), argv = require('optimist').argv, exec = require('child_process').exec; exports.run = function (option) { var maniDir = path.join(process.cwd(), 'Manifest.xml'); var oldVer = getVersion(maniDir); if (option.version !== oldVer) { updateManifest(maniDir, option); } pkg(option); }; exports.getVer = function (rootDir) { var packageVer = getVersion(path.join(rootDir, 'Manifest.xml')); if (!packageVer) { throw new Error('version not found in Manifest'); } return packageVer; }; function updateManifest(maniDir, option) { var mstr = fs.readFileSync(maniDir).toString(); mstr = mstr.replace(/(<version>)(.*)(<\/version>)/, '$1' + option['version'] + '$3'); fs.writeFileSync(maniDir, mstr); } var pkg = function (option) { var rootDir = process.cwd(); //开发版本 var environ = option['environ']; //获取dist目录 var distDir = path.join(rootDir, 'dist'); //获取package根目录 var packageDir = path.join(rootDir, 'package'); //准备需打包的项目文件 prepare(distDir, rootDir); pack(rootDir, packageDir, distDir, environ); }; // 打包成amr function pack(rootDir, packageDir, distDir, environ) { //获取版本号 var packageVer = getVersion(path.join(rootDir, 'Manifest.xml')); if (!packageVer) { throw new Error('version not found in Manifest'); } //获取应用id var packageId = getPackageId(path.join(rootDir, 'Manifest.xml')); if (!packageId) { throw new Error('appid not found in Manifest'); } if (!fs.existsSync(packageDir)) { fs.mkdirsSync(packageDir); } process.chdir(distDir); var amr = path.join(packageDir, packageId + '-' + packageVer + '_' + environ + '.amr'); if (fs.existsSync(amr)) { fs.removeSync(amr); } console.log('# archiving...'); exec("zip -r '" + amr + "' *", function (err, stdout, stderr) { console.log('# packed at ' + amr.green); process.exit(0); }); } // 预备文件 function prepare(_distDir, _rootDir) { var files; if (fs.existsSync(_distDir)) { fs.removeSync(_distDir); } fs.mkdirsSync(_distDir); var srcArr = ['res', 'www', 'Manifest.xml']; while (srcArr.length) { var name = srcArr.pop(); var pathname = path.join(_rootDir, name); if (fs.existsSync(pathname)) { copySync(pathname, path.join(_distDir, name), [/debug\.js$/, /^alipay\.js$/]); } else { files = false; console.log(name + " not exist,check it please!"); break; } } files !== false && (files = scan(_distDir)); return files; } // 扫描目录, 删除不使用的文件 function scan(dir, del, base, out) { del = del || function (x) { return x[0] == '.' || x == 'CERT'; }; base = base || dir; out = out || []; fs.readdirSync(dir).forEach(function (name) { var fname = path.join(dir, name); if (del(name)) { fs.unlinkSync(fname); } else if (fs.statSync(fname).isDirectory()) { scan(fname, del, base, out); } else { out.push(fname.slice(base.length + 1)); } }); return out; } // 复制文件或目录, follow src中的符号链接 // dst只能是目标本身, 而非目标所在目录; 已存在的dst会被删除 // copy时文件整个读到内存 // 没有考虑符号链接无穷递归的情况 function copySync(src, dst, ignores) { var dir = path.dirname(src); var stats = fs.lstatSync(src); if (stats.isSymbolicLink()) { return copySync(path.resolve(dir, fs.readlinkSync(src)), dst, ignores); } if (stats.isDirectory()) { if (!fs.existsSync(dst)) { fs.mkdirsSync(dst); } fs.readdirSync(src).forEach(function (name) { for (var i = 0; i < (ignores || []).length; ++i) { if (ignores[i].test(name)) { return; } } copySync(path.join(src, name), path.join(dst, name), ignores); }); } else { var dstDir = path.dirname(dst); if (!fs.existsSync(dstDir)) { fs.mkdirsSync(path.dirname(dst)); } else if (fs.existsSync(dst)) { fs.removeSync(dst); } fs.writeFileSync(dst, fs.readFileSync(src)); } } // 读取Manifest里的版本号 function getVersion(fname) { var match = fs.readFileSync(fname).toString().match(/<version>(.+)<\/version>/); return match && match[1]; } function getPackageId(fname) { var match = fs.readFileSync(fname).toString().match(/<uid>(.+)<\/uid>/); return match && match[1]; }
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { observer, get, computed } from '@ember/object'; import { reads } from '@ember/object/computed'; import move from 'ember-animated/motions/move'; import layout from './template'; import { getLayout, measureText } from 'dom-ruler'; import { bind, debounce } from '@ember/runloop'; export default Component.extend({ layout, duration: 300, classNames: ['navigation-bar'], router: service(), intl: service(), fileQueue: service(), progress: reads('fileQueue.progress'), init() { this._super(); this.didTransition(); this.set('visibleRoutes', ['home']); }, displayDuration: computed('isMeasuring', 'duration', function () { return this.isMeasuring ? 0 : this.duration; }), scheduleMeasurement() { this.set('isMeasuring', true); debounce(() => { if (this.isDestroyed) return; this.set('isMeasuring', false); this.measure(); }, 10); }, didInsertElement() { this.measure(); this.resize = bind(this, 'scheduleMeasurement'); window.addEventListener('resize', this.resize); }, willDestroyElement() { window.removeEventListener('resize', this.resize); }, *slide({ insertedSprites, removedSprites }) { insertedSprites.map((sprite) => { sprite.startAtPixel({ x: 0, y: sprite.finalBounds.height * -1 + 36 }); return move(sprite); }); removedSprites.map((sprite) => { sprite.endAtPixel({ x: 0, y: sprite.initialBounds.height * -1 + 36 }); return move(sprite); }); yield; }, mobileRoutes: computed('routes', function () { return this.routes.split(' '); }), measure() { if (this.element.querySelector('a') == null || this.element.querySelector('nav') == null) { return; } let routes = [...this.routes.split(' '), 'more'].map((routeName) => { return { routeName, width: measureText(this.intl.t(`navigation.${routeName}`), { whiteSpace: 'nowrap', marginRight: '0.25rem' }, { template: this.element.querySelector('a') }).margins.width }; }); let more = routes.pop(); let space = getLayout(this.element.querySelector('nav')).content.width - more.width; let submit = this.element.querySelector('.submit-button'); if (submit) { space -= getLayout(submit).margins.width; } let visible = []; let invisible = routes; while (space > 0 && invisible.length > 0) { let route = invisible.shift(); space -= route.width; visible.push(route); } if (space < 0) { invisible.unshift(visible.pop()); } this.set('visibleRoutes', visible.map((route) => route.routeName)); this.set('hiddenRoutes', invisible.map((route) => route.routeName)); }, didTransition: observer('router.currentRouteName', function () { get(this, 'router.currentRouteName'); // Necessary for triggering observation this.set('isActive', false); }) });
angular.module('geoChat').controller("geoChatAppController", function($scope, $firebaseObject, $firebaseArray, $geofire) { $scope.logged=false; $scope.entrar= function(usuario){ var usuarios = new Firebase("https://glaring-heat-1935.firebaseio.com/usuarios"), users = new GeoFire(usuarios), obj = $firebaseObject(usuarios); users.get(usuario).then(function(location) { if (location === null) { console.log("Provided key is not in GeoFire"); } else { //Si existe mirar si esta conectado console.log("Provided key has a location of " + location); } }, function(error) { console.log("Error: " + error); }); $scope.$root.usuario = usuario; //$scope.logged=true; }; });
var child_process = require('child_process'); module.exports = function useradd(options, callback) { if (typeof options === 'string') { options = { login: options }; } var args = []; if (options.gid) { args.push('-g', options.gid); } if (typeof options.shell !== 'undefined') { if (options.shell === false) { args.push('-s', '/bin/false'); } else { args.push('-s', options.shell); } } if (typeof options.home !== 'undefined') { if (options.home === true) { args.push('-m'); } else if (options.home === false) { if (process.platform !== 'sunos') { // // SunOS doesn't support -M and doesn't create home directory by // default. // args.push('-M'); } } else { args.push('-d', options.home); } } args.push(options.login); var child = child_process.spawn(options.executable || 'useradd', args); child.on('exit', function (code) { var err; if (code) { err = new Error('Invalid exit code: ' + code); err.code = code; return callback(err); } callback(); }); };
var todomvc = angular.module('todomvc', []);
'use strict' import Vue from 'vue'; import VueRouter from 'vue-router'; import filters from './filters'; import routerMap from './routers'; import FastClick from 'fastclick'; Vue.use(VueRouter); $.ajaxSettings.crossDomain = true; //实例化Vue的filter Object.keys(filters).forEach(k => Vue.filter(k, filters[k])); //实例化VueRouter let router = new VueRouter({ hashbang: true, history: false, saveScrollPosition: true, transitionOnLoad: true }); //登录中间验证,页面需要登录而没有登录的情况直接跳转登录 router.beforeEach((transition) => { //处理左侧滚动不影响右边 $("html, body, #page").removeClass("scroll-hide"); FastClick.attach(document.body); if (transition.to.auth) { if (localStorage.userId) { transition.next(); } else { var redirect = encodeURIComponent(transition.to.path); transition.redirect('/login?redirect=' + redirect); } } else { transition.next(); } }); // 路由器需要一个根组件 let app = Vue.extend({}); routerMap(router); // 启动应用 // 路由器会创建一个 App 实例,并且挂载到选择符 #app 匹配的元素上。 router.start(app, "#app");
/** * Created by alextishin on 06.06.17. */ import React, {Component} from 'react'; import {Link} from 'react-router' import shortid from 'shortid' import './styles.css'; class Menu extends Component { constructor(props) { super(props); this.state = { items: props.items.map((item) => { if(!item.id) { return {...item, id: shortid.generate()}; //return Object.assign({}, item, {id: shortid.generate()}); } return {...item}; }), selectedId: null } } static propTypes = { layout: React.PropTypes.string, items: React.PropTypes.arrayOf(React.PropTypes.object).isRequired } static defaultProps = { layout: 'x' }; getLayoutClass = () => { return this.props.layout == 'x' ? 'hmenu' : 'vmenu'; } renderItems(layout){ return this.state.items.map((navItem) => { return ( <li key={shortid.generate()} className={`${layout}__item`}> <Link to={navItem.pathname} className={`menu__link`}>{navItem.name}</Link> </li> ) }); } render() { let layout = this.getLayoutClass(); return ( <div className="menu"> <ul className={layout}> {this.renderItems(layout)} </ul> </div> ) } } export default Menu;
/* * Helma License Notice * * The contents of this file are subject to the Helma License * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. A copy of the License is available at * http://adele.helma.org/download/helma/license.txt * * Copyright 1998-2006 Helma Software. All Rights Reserved. * * $RCSfile: Skin.js,v $ * $Author: zumbrunn $ * $Revision: 8714 $ * $Date: 2007-12-13 13:21:48 +0100 (Don, 13 Dez 2007) $ */ /** * @fileoverview Fields and methods of the helma.Skin class. * <br /><br /> * To use this optional module, its repository needs to be added to the * application, for example by calling app.addRepository('modules/helma/Skin.js') */ // define the helma namespace, if not existing if (!global.helma) { global.helma = {}; } /** * Constructs a new instance of helma.Skin * @class Instances of this class represent a Helma skin. In addition * to the standard skin functionality this class allows creation of * a skin based on a Base64 encoded source. * @param {String} source The source of the skin * @param {Boolean} encFlag If true the source will be Base64-decoded. * @constructor * @returns A newly created instance of helma.Skin */ helma.Skin = function(source, encFlag) { /** @ignore */ var Base64 = Packages.helma.util.Base64; if (!encFlag) { var skin = createSkin(source); } else { var encoded = source; source = new java.lang.String(source); var bytes = Base64.decode(source.toCharArray()); var skin = createSkin(new java.lang.String(bytes, "UTF-8")); } /** @ignore */ this.toString = function() { return source; }; /** * Returns the source of the skin as Base64 encoded string * @returns The source of the skin as Base64 encoded string * @type String */ this.valueOf = function() { if (encFlag) { return encoded; } var bytes = new java.lang.String(source).getBytes("UTF-8"); return new java.lang.String(Base64.encode(bytes)); }; /** * Renders the skin. * @param {Object} param An optional parameter object to pass to the skin. */ this.render = function(param) { return renderSkin(skin, param); }; /** * Returns the rendered skin. * @param {Object} param An optional parameter object to pass to the skin. * @type String */ this.renderAsString = function(param) { return renderSkinAsString(skin, param); }; /** * Returns true if the skin contains a macro with the name * and optional handler passed as argument. * @param {String} name The name of the macro * @param {String} handler An optional macro handler name * @returns True if the skin contains this macro at least once, * false otherwise. * @type Boolean */ this.containsMacro = function(name, handler) { res.push(); res.write("<% *"); if (handler) { res.write(handler); res.write("."); } res.write(name); res.write(" *%>"); var re = new RegExp(res.pop(), "g"); return re.test(source); }; for (var i in this) this.dontEnum(i); return this; }; helma.lib = "Skin"; helma.dontEnum(helma.lib); for (var i in helma[helma.lib]) helma[helma.lib].dontEnum(i); for (var i in helma[helma.lib].prototype) helma[helma.lib].prototype.dontEnum(i); delete helma.lib;
/** * initialize-large-card-data * Created by dcorns on 6/5/17 * Copyright © 2017 Dale Corns * MIT Licensed * Set the textContent of view.partN and view.addTxtN to parstAry[even] and partsAry[odd] */ 'use strict'; module.exports = (view, parts) => { let viewIdx = 0; parts.partList.forEach((item, i) => { if(i%2 === 0){ view[`part${viewIdx}`].textContent = item; } else { view[`addTxt${viewIdx}`].textContent = item; viewIdx++; } }); view.largeCardSubTitle.textContent = `Winning Ticket: ${parts.winner}`; };
// This file is part of Indico. // Copyright (C) 2002 - 2022 CERN // // Indico is free software; you can redistribute it and/or // modify it under the terms of the MIT License; see the // LICENSE file for more details. import {connect} from 'react-redux'; import {clearError, showReportForm} from './actions'; import ErrorDialog from './component'; const mapStateToProps = ({errors: {errorList, formVisible}}) => ({ errorData: errorList[0], remainingErrors: errorList.length ? errorList.length - 1 : 0, formVisible, dialogVisible: !!errorList.length, }); const mapDispatchToProps = dispatch => ({ showReportForm() { dispatch(showReportForm()); }, clearError() { dispatch(clearError()); }, }); export default connect( mapStateToProps, mapDispatchToProps )(ErrorDialog);
import React from 'react'; import ReactDOM from 'react-dom'; import moment from 'moment'; import Slider from 'rc-slider/lib/Slider'; const LabelForDay = ({value, day, handler}) => <span className={value === day ? "label label-primary" : "label label-default"} onClick={() => handler(day)} > { day === 0 ? 'Today' : moment().add(day, 'day').format('DD/MM')} </span> const range = (from, to) => Array.from({length: to-from+1}, (v, i) => i+from) const SpentForm = ({handleSubmit, handleInputChange, handleSliderChange, handleDayChange, spent}) => <form onSubmit={handleSubmit} > <div className="row"> <div className="col-md-12 text-center"> <div> {range(-3,2).map(day => <LabelForDay key={day} value={spent.day} day={day} handler={handleDayChange} />) } </div> around {spent.hour}hs <Slider max={23} onChange={handleSliderChange} value={spent.hour}/> </div> </div> <div className="row"> <div className="col-md-4"> <div className="form-group "> <label className="control-label">Success inputs</label> <input type="number" tabIndex="1" name="cost" value={spent.cost} onChange={handleInputChange} placeholder="costo" className="form-control" /> <span className="material-input"></span> </div> </div> <div className="col-md-4"> <div className="form-group "> <label className="control-label">Success input</label> <input type="text" value={spent.name} name="name" tabIndex="2" onChange={handleInputChange} placeholder="nombre" className="form-control" /> <span className="material-input"></span> </div> </div> <div className="col-md-4"> <div className="form-group "> <button className="btn btn-danger">egreso</button> </div> </div> </div> </form> class SpentFormClass extends React.Component { constructor(props) { super(props) this.state = this.initialState() } initialState = () => ({ cost: '', hour: parseInt(moment().format("HH")), day: 0, name: '', }) handleDayChange = (value) => { this.setState({ ["day"] : value, }) } handleSliderChange = (value) => { this.setState({ ["hour"] : value }) } handleInputChange = (event) => { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } handleSubmit = (e) => { e.preventDefault() if (this.state.cost === '' && !(parseInt(this.state.cost) > 0)) return; this.props.onSubmit({ cost: parseInt(this.state.cost), name: this.state.name, quantity: 1, when: moment().add(this.state.day,'day').hours(this.state.hour).format('YYYY-MM-DDTHH:mm:ss') }) this.setState( this.initialState ) } render() { return <SpentForm spent={this.state} handleSubmit={this.handleSubmit} handleDayChange={this.handleDayChange} handleSliderChange={this.handleSliderChange} handleInputChange={this.handleInputChange} />; } } export default SpentFormClass
/** * Created by dierickx.len on 01/04/2017. */ import is from '../is' const isFunction = is('Function') /** * @function isIterator * @param {iterator} iter - Accepts an iterator which can be an array, map or any other custo, implemented iterator * @returns {boolean} */ export default function isIterator (iter) { return isFunction(iter[Symbol.iterator]) }
var progressBar = document.getElementById("progress"); var fileInput = document.getElementById("project-file"); var importForm = document.getElementById("import-form"); function upload(){ if (fileInput.files.length==0){ alert('Please choose 1 file!'); return; } if(fileInput.files[0].type!=='application/x-zip-compressed'){ alert('Please choose a zip file!'); return; } var request = new XMLHttpRequest(); request.upload.onprogress = function(event){ progressBar.value = Math.round((event.loaded / event.total) * parseInt(progressBar.max)); }; request.onload = function(){ if(request.status == 200){ if(request.responseText) alert(request.responseText); else document.location.reload(); } else alert("File upload failed!"); }; progressBar.value = 0; request.open('POST', 'import', true); request.send(new FormData(importForm)); }
import create from 'lodash/create' import createEventRegistry from './eventRegistry' import { observable } from 'mobservable' /* Augment a feathers client (v2.0.1) with: - auto-reauthentication on disconnect/reconnect - new events: "authenticated" & "disconnect" */ const authenticateWithRetry = function(feathersClient, eventRegistry, credentials) { if (feathersClient.io.connected) { return new Promise(function(resolve, reject) { eventRegistry.once(feathersClient.io, 'disconnect', function() { feathersClient.emit('disconnect') console.log('feathers client disconnected') authenticateWithRetry(feathersClient, eventRegistry, credentials).then(resolve).catch(reject) }) feathersClient.authenticate(credentials) .then(function() { feathersClient.emit('authenticated') console.log('reauthenticated') resolve() }) .catch(err => { feathersClient.emit('notAuthenticated') console.log('not-authenticated', err) reject(err) }) }) } else { return new Promise(function(resolve, reject) { eventRegistry.once(feathersClient.io, 'connect', function() { console.log('connected') authenticateWithRetry(feathersClient, eventRegistry, credentials).then(resolve).catch(reject) }) }) } } export default function (feathersClient) { const eventRegistry = createEventRegistry() const $isAuthenticated = observable(false) return create(feathersClient, { isAuthenticated: () => $isAuthenticated(), authenticate: function(credentials) { if ($isAuthenticated()) { throw "authenticate() cannot be called twice unless you logout" } $isAuthenticated('authenticating') return authenticateWithRetry(feathersClient, eventRegistry, credentials) .then(() => { $isAuthenticated(true) }) .catch(err => { $isAuthenticated(false) throw err }) }, logout: function() { // clear listeners eventRegistry.clear() feathersClient.logout() $isAuthenticated(false) feathersClient.emit('notAuthenticated') }, on: feathersClient.on.bind(feathersClient), emit: feathersClient.emit.bind(feathersClient), }) }
/* Copyright 2017 Ronny Reichmann */ /* global test expect */ const pipe = require('./pipe') test('pipe.event', done => { function receiveSendFn (msg) { let count = 0 msg.event .forEach(event => { count++ if (count === 100) { expect(true).toBe(true) done() } }) } const pattern = { role: 'event' } const eventEmitterFn = pipe.event(receiveSendFn)(pattern) for (var i = 0; i < 100; i++) { eventEmitterFn({ type: 'test', index: i }) } })
import React from 'react'; import PropTypes from 'prop-types'; const Grid = ({ fill, ...props }) => <svg fill={fill} viewBox="0 0 24 24" {...props}> <path d="M0 0h24v24H0z" fill="none" /> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 20H4v-4h4v4zm0-6H4v-4h4v4zm0-6H4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4z" /> </svg>; Grid.propTypes = { fill: PropTypes.string, }; Grid.defaultProps = { fill: 'currentColor', }; export default Grid;
var webpack = require('webpack'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var CopyWebpackPlugin = require("copy-webpack-plugin"); var path = require("path"); var join = path.join.bind(path, __dirname); module.exports = { cache: true, devtool: "inline-source-map", entry: [ './docs-src/app.ts', './docs-src/docs.less' ], output: { path: path.resolve('./docs'), filename: 'app.js', publicPath: "/cycle-semantic-ui/" }, module: { rules: [ { test: /\.less$/, loader: ExtractTextPlugin.extract({ loader:[ 'css-loader', 'less-loader'], fallbackLoader: 'style-loader' }) }, { test: /\.css$/, loader: ExtractTextPlugin.extract({ loader:['css-loader'], fallbackLoader: 'style-loader' }) }, { test: /\.ts$/, loader: 'ts-loader', options: { configFileName: "./docs-src/tsconfig.json" } }, { test: /\.(ttf|eot|svg|otf|woff(2)?|png)(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: "file-loader?name=[name].[ext]", } ] }, devServer: { historyApiFallback: { index: '/cycle-semantic-ui/', // rewrites: [ // { from: /^\/$/, to: '/cycle-semantic-ui/index.html' }, // ] } }, resolve: { extensions: ['.js', '.ts'], modules: [ path.resolve("./docs-src"), "./src", "node_modules" ] }, plugins: [ new CopyWebpackPlugin([{ from: "./docs-src/index.html" }, { from: "./docs-src/404.html" }]), new ExtractTextPlugin({ filename: "bundle.css", disable: false, allChunks: true }) ] };
/** * # Exporter widget for nodeGame * Copyright(c) 2021 Stefano Balietti * MIT Licensed * * Manage chats with clients. * * www.nodegame.org * --- */ (function(node) { "use strict"; node.widgets.register('Exporter', Exporter); const Table = W.Table; // ## Meta-data Exporter.version = '0.3.0'; Exporter.description = 'Exports data and logs'; Exporter.title = 'Export Data/Logs <em>(Experimental)</em>'; Exporter.className = 'exporter'; // ## Dependencies Exporter.dependencies = {}; function Exporter() { this.selectStr = 'Select a game'; this.inProgress = null; } Exporter.prototype.append = function() { this.panelDiv.classList.add('h-100'); let radioGroup = ` <div class="btn-group" role="group" aria-label="Log or Data Group"> <input type="radio" class="btn-check" name="radio-export" id="radio-export-data" autocomplete="off" checked> <label class="btn btn-outline-primary" for="radio-export-data">Data</label> <input type="radio" class="btn-check" name="radio-export" id="radio-export-logs" autocomplete="off"> <label class="btn btn-outline-primary" for="radio-export-logs">Logs</label> </div> <div class="btn-group" role="group" aria-label="Export Group"></div> `; // Containers for buttons.. let div = W.add('div', this.bodyDiv, { style: { margin: '10px 0 15px 0' }, className: 'btn-toolbar justify-content-between', innerHTML: radioGroup }); this.logsBtn = this.bodyDiv.querySelector('#radio-export-logs'); this.logsBtn.addEventListener('click', () => { if (this.inProgress) return; this.expBtn.disabled = false; }); this.dataBtn = this.bodyDiv.querySelector('#radio-export-data'); this.dataBtn.addEventListener('click', () => { if (this.dropdownBtn.innerHTML === this.selectStr) { this.expBtn.disabled = true; } }); let btnGroup = div.querySelectorAll('.btn-group')[1]; // Show 'Send' button. let btnGroupDropdown = W.add('div', btnGroup, { className: 'btn-group', role: 'group' }); this.dropdownBtn = W.add('button', btnGroupDropdown, { className: 'btn btn-outline-dark dropdown-toggle', type: 'button', 'data-bs-toggle': 'dropdown', 'aria-expanded': false, innerHTML: this.selectStr, // id: 'exporter-game-btn' }); // Show 'Send' button. this.gameSelector = W.add('ul', btnGroupDropdown, { className: 'dropdown-menu', // 'aria-labelled-by': 'exporter-game-btn' }); this.gameSelector.onclick = (e) => { let game = e.target.innerHTML; this.dropdownBtn.innerHTML = game; let noGame = game === this.selectStr; this.gameSelected = noGame ? null : game; if (!this.logsBtn.checked) this.expBtn.disabled = noGame; }; populateGameSel(this); // Show 'Send' button. this.expBtn = W.add('button', btnGroup, { className: 'btn btn-primary', innerHTML: 'Export', disabled: true }); this.expBtn.onclick = () => { this.expBtn.disabled = true; this.expBtn.innerHTML = 'In progress'; this.inProgress = setTimeout(() => { this.expBtn.disabled = false; this.expBtn.innerHTML = 'Export'; this.inProgress = null; }, 15000); let rnd = J.randomInt(1000000000); node.once.data('exported', (msg) => { if (msg.data.idx !== rnd) return; node.game.alert('Export completed.'); this.expBtn.disabled = false; this.expBtn.innerHTML = 'Export'; clearTimeout(this.inProgress); this.inProgress = null; }); let type = this.logsBtn.checked ? 'LOGS' : 'DATA'; let msg = { target: 'SERVERCOMMAND', text: 'EXPORT', data: { type: type, idx: rnd, options: textarea.value } }; if (this.gameSelected) msg.data.game = this.gameSelected; msg = node.msg.create(msg); if (msg) node.socket.send(msg); }; // Show a button that expands the table of advanced fields. let textarea = W.add('textarea', this.bodyDiv, { placeholder: 'options, e.g, --out-format csv' }); }; Exporter.prototype.listeners = function() { node.on('CHANNEL_SELECTED', () => populateGameSel(this) ); }; const populateGameSel = that => { let gameSel = that.gameSelector; gameSel.innerHTML = ''; W.add('li', gameSel, { innerHTML: that.selectStr, class: 'dropdown-item' }); W.add('li', gameSel, { innerHTML: '<hr class="dropdown-divider">' }); let chanInUse = node.game.channelInUse; if (chanInUse) { W.add('li', gameSel, { innerHTML: chanInUse, class: 'dropdown-item' }); W.add('li', gameSel, { innerHTML: '<hr class="dropdown-divider">' }); } for (let g in node.game.gamesInfo) { if (node.game.gamesInfo.hasOwnProperty(g) && g !== chanInUse) { W.add('li', gameSel, { innerHTML: g, class: 'dropdown-item' }); } } } })(node);
import {EventEmitter} from 'events'; import expect from 'expect.js'; import CompactLog from '../'; import Namespace from '../build/namespace'; describe('core', () => { let log; let ns; describe('basics', () => { it('create instance', () => { log = new CompactLog(); expect(log).to.be.an(CompactLog); expect(log).to.be.an(Namespace); expect(log).to.be.an(EventEmitter); }); }); describe('namespaces', () => { it('create instance', () => { ns = log.createNamespace(); expect(ns).to.be.an(Namespace); expect(ns.id).to.be(1); }); it('create multiple instances', () => { for (let i = 0; i < 10; i++) { let ns = log.createNamespace(); expect(ns).to.be.an(Namespace); expect(ns.id).to.be(i+2); } }); it('gets parents', () => { expect(log.getParents()).to.eql([]); expect(ns.getParents()).to.eql([0]); }); it('gets parents (multiple)', () => { let cLog = new CompactLog(); let subNS = cLog.createNamespace(); let sub2NS1 = subNS.createNamespace(); let sub2NS2 = subNS.createNamespace(); let sub2NS3 = subNS.createNamespace(); let sub3NS = sub2NS2.createNamespace(); let sub4NS = sub3NS.createNamespace(); expect(cLog.getParents()).to.eql([]); expect(subNS.getParents()).to.eql([0]); expect(sub2NS1.getParents()).to.eql([1, 0]); expect(sub2NS2.getParents()).to.eql([1, 0]); expect(sub2NS3.getParents()).to.eql([1, 0]); expect(sub3NS.getParents()).to.eql([3, 1, 0]); expect(sub4NS.getParents()).to.eql([5, 3, 1, 0]); }); }); });
/** * Module dependencies. */ 'use strict' const Counter = require('passthrough-counter') const humanize = require('humanize-number') const bytes = require('bytes') const chalk = require('chalk') /** * Expose logger. */ module.exports = dev /** * Color map. */ const colorCodes = { 7: 'magenta', 5: 'red', 4: 'yellow', 3: 'cyan', 2: 'green', 1: 'green', 0: 'yellow' } /** * Development logger. */ function dev (opts) { return async function logger (ctx, next) { // request const start = Date.now() console.log(' ' + chalk.gray('<--') + ' ' + chalk.bold('%s') + ' ' + chalk.gray('%s'), ctx.method, ctx.originalUrl) try { await next() } catch (err) { // log uncaught downstream errors log(ctx, start, null, err) throw err } // calculate the length of a streaming response // by intercepting the stream with a counter. // only necessary if a content-length header is currently not set. const length = ctx.response.length const body = ctx.body let counter if (length == null && body && body.readable) { ctx.body = body .pipe(counter = Counter()) .on('error', ctx.onerror) } // log when the response is finished or closed, // whichever happens first. const res = ctx.res const onfinish = done.bind(null, 'finish') const onclose = done.bind(null, 'close') res.once('finish', onfinish) res.once('close', onclose) function done (event) { res.removeListener('finish', onfinish) res.removeListener('close', onclose) log(ctx, start, counter ? counter.length : length, null, event) } } } /** * Log helper. */ function log (ctx, start, len, err, event) { // get the status code of the response const status = err ? (err.status || 500) : (ctx.status || 404) // set the color of the status code; const s = status / 100 | 0 const color = colorCodes.hasOwnProperty(s) ? colorCodes[s] : 0 // get the human readable response length let length if (~[204, 205, 304].indexOf(status)) { length = '' } else if (len == null) { length = '-' } else { length = bytes(len).toLowerCase() } const upstream = err ? chalk.red('xxx') : event === 'close' ? chalk.yellow('-x-') : chalk.gray('-->') console.log(' ' + upstream + ' ' + chalk.bold('%s') + ' ' + chalk.gray('%s') + ' ' + chalk[color]('%s') + ' ' + chalk.gray('%s') + ' ' + chalk.gray('%s'), ctx.method, ctx.originalUrl, status, time(start), length) } /** * Show the response time in a human readable format. * In milliseconds if less than 10 seconds, * in seconds otherwise. */ function time (start) { const delta = Date.now() - start return humanize(delta < 10000 ? delta + 'ms' : Math.round(delta / 1000) + 's') }
/* * File : instance.spec.js * Description : TEST instance method. * ------------------------------------------------------------------------------------------------ */ "use strict"; var path = require("path"), essencejs; module.exports = { setUp : function (callback) { essencejs = new (require(process.cwd()).EssenceJs)(); callback(); }, tearDown : function(callback) { essencejs.dispose(); callback(); }, "Check that instance prototype is equal to the register prototype method": function (test) { test.expect(1); test.equal(essencejs.instance, essencejs.register); test.done(); }, "Register something using the instance method": function (test) { test.expect(1); var TestClass = function TestClass() { }; essencejs.instance(TestClass); test.equal(essencejs.isRegistered("TestClass"), true, "Expected the `TestClass` key to return true"); test.done(); } };
/* eslint-disable */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import ProfileCard from './components/profileCard'; import Annotation from './components/annotation'; import getRecentUserAnnotations, { fetchUserProfileInfo } from './actions'; /* eslint-enable */ // const hasBeenExecuted = false; let profileId = window.location.href.substr(window.location.href.lastIndexOf('/') + 1); class Profile extends Component { componentDidMount() { profileId = window.location.href.substr(window.location.href.lastIndexOf('/') + 1); Promise.resolve(this.props.dispatch(fetchUserProfileInfo(profileId))).then(() => this.props.dispatch(getRecentUserAnnotations(profileId))); } // componentWillReceiveProps(nextProps) { // if ( // nextProps.userId && !hasBeenExecuted // ) { // this.props.dispatch(getRecentUserAnnotations(nextProps.userId)); // hasBeenExecuted = true; // } // } /* eslint-disable */ render() { const isUsersProfile = profileId === this.props.userId; let name = 'Anonymous'; if (this.props.info.name) { name = this.props.info.name; const filteredName = name.split(' '); if (filteredName.length >= 2) { if (filteredName[1].charAt(0)) { // If it's not null name = `${`${filteredName[0]} ${filteredName[1][0]}`}.`; } } } return ( <div> <ProfileCard userId={this.props.userId} isUsersProfile={isUsersProfile} profileId={profileId} info={this.props.info} /> {this.props.recentAnnotations !== [] || this.props.recentAnnotations !== null ? this.props.recentAnnotations.map((annotation, i) => { return <Annotation key={i} annotation={annotation} />; }) : ''} </div> ); } /* eslint-enable */ } Profile.defaultProps = { recentAnnotations: [], }; const mapStateToProps = state => ({ userId: state.user ? state.user._id : '', recentAnnotations: state.Profile ? state.Profile.recentAnnotations : [], info: state.Profile ? state.Profile.info : {}, }); export default connect(mapStateToProps)(Profile);
// exposing a public api export { default } from './StyledChild';
chrome.extension.onRequest.addListener(function(frameworks, sender){ if (frameworks.length == 0) return; if (!sender.tab.url.match(/^https?:\/\//)) return; var tabId = sender.tab.id; var title = frameworks.map(function(framework){ if (framework.version) { return framework.name + ' (' + framework.version + ')'; } else { return framework.name; } }).join('\n'); chrome.pageAction.setTitle({tabId: tabId, title: title}); chrome.pageAction.setIcon({ tabId: tabId, imageData: createIcon(frameworks[0].abbr) }); var popup = 'popup.html#' + encodeURIComponent(JSON.stringify(frameworks)) chrome.pageAction.setPopup({tabId: tabId, popup: popup}) chrome.pageAction.show(tabId); }); function createIcon(text) { var ctx = document.createElement('canvas').getContext('2d'); var w = 19; var h = 19; var rad = 3; // border radius var lw = 1; // line width var hlw = lw/2; // half line width var t = hlw + 1; var r = w - hlw; var b = h - hlw - 1; var l = hlw; // box path ctx.beginPath(); ctx.moveTo(l, (t + b) / 2); ctx.arcTo(l, t, r, t, rad); ctx.arcTo(r, t, r, b, rad); ctx.arcTo(r, b, l, b, rad); ctx.arcTo(l, b, l, t, rad); ctx.closePath(); // box background var grad = ctx.createLinearGradient(0, t, 0, b); grad.addColorStop(0, '#6ee'); grad.addColorStop(0.1, '#5BC0DE'); grad.addColorStop(1, '#2F96B4'); ctx.fillStyle = grad; ctx.fill(); // box border ctx.lineWidth = lw; ctx.strokeStyle = '#2F96B4'; ctx.stroke(); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; // text shadow ctx.fillStyle = 'rgba(0, 0, 0, 0.25)'; ctx.fillText(text, w/2, h/2 - 1, w - 2); // text ctx.fillStyle = '#fff'; ctx.fillText(text, w/2, h/2, w - 2); return ctx.getImageData(0, 0, w, h); }
define(['services/services'], function (services) { 'use strict'; services.service('$bootstrap', function ($timeout, $rootScope, $route) { var ready = false; var progress = 0; this.isReady = function () { return ready; }; this.ready = function () { ready = true; $timeout(function () { if (!$route.current) { $route.reload(); } $rootScope.$broadcast('coreReady', true); }, 500); }; this.getProgress = function () { return progress; }; this.setProgress = function (value) { progress = value; }; }); services.run(function ($rootScope, $bootstrap) { $rootScope.$on('$locationChangeStart', function (event) { if (!$bootstrap.isReady()) { return event.preventDefault(); } }); }); });
var writer__base_8h = [ [ "writer_type", "namespacehryky.html#a6e4ff4323d21008491448b85560f120f", null ], [ "reduce", "namespacehryky_1_1writer.html#a06f60ef7e1d7956768fbd47e448b9559", null ], [ "swap", "namespacehryky_1_1writer.html#adc1a7ebf722aa57a21b0df16d44cc7b7", null ] ];
'use strict'; function $(argName) { return { $: $, argName: argName }; } module.exports = function (obj, defaultPosition) { defaultPosition = (defaultPosition || defaultPosition === 0) ? defaultPosition : -1; var prototype = {}; function createPointlessWrapper(func) { return function () { var args = []; var pf = [func, args, -1, []]; var specific = false; for (var i = 0; i < arguments.length; i++) { if (arguments[i] === $) { pf[2] = i; specific = true; break; } } for (i = 0; i < arguments.length; i++) { if (i === defaultPosition && !specific) { args.push(null); args.push(arguments[i]); } else { args.push(arguments[i]); if (arguments[i].$ === $) { pf[3].push([(!specific && defaultPosition > -1 && i > defaultPosition ? 1 : 0) + i, arguments[i].argName]); } } } this._chain.push(pf); return this; }; } for (var key in obj) { if (obj.hasOwnProperty(key)) { var value = obj[key]; if (typeof value === 'function') { prototype[key] = createPointlessWrapper(value); } } } return function (pointPosition) { pointPosition = (pointPosition || pointPosition === 0) ? pointPosition : -1; function pointlessObj() { var point = arguments[pointPosition === -1 ? (arguments.length - 1) : pointPosition]; pointlessObj._chain.forEach(function (pf) { var f = pf[0]; var args = pf[1]; var $pos = pf[2]; var namedArgs = pf[3]; if ($pos > -1) { args[$pos] = point; } else if (defaultPosition === -1) { args[args.length - 1] = point; } else { args[defaultPosition] = point; } for (var i = 0; i < namedArgs.length; i++) { var namedArg = namedArgs[i][1]; args[namedArgs[i][0]] = arguments[namedArg]; } point = f.apply(obj, args); }); return point; } pointlessObj._chain = []; for (var key in prototype) { pointlessObj[key] = prototype[key]; } return pointlessObj; }; }; module.exports.$ = $;
#!/usr/bin/env node // TODO: this script sucks; usage on empty, actual validation, ect. const fs = require('fs'); const path = require('path'); const program = require('commander'); const slsperf = require(path.join(__dirname, '..')); let config = { provider: {}, function: {}, test: {} }; let latencyTest = { type: 'latency', delayCallback: i => 60000 * (Math.floor((i - 1) / 5) + 1), maxDelay: 1800000 }; let throughputTest = { type: 'throughput', width: 15, duration: 10000, }; let keepAliveTest = { type: 'latency', delayCallback: i => i ? 0 : 100, maxDelay: 101 }; program .usage('[options] <resultsDirectory>') .option( '-p, --provider <name>', 'Serverless platform to target (amazon, ibm, microsoft, google, prototype)', name => config.provider.name = name == 'google' ? 'alphabet' : name) .option( '--project <name>', 'Name of the project to deploy Google Cloud Functions to', name => config.provider.project = name) .option( '--credentials <path>', 'Path of the file holding Google Cloud credentials', path => config.provider.credentials = path) .option( '-d, --duration <ms>', 'Number of milliseconds the function should execute before returning', ms => config.function.duration = parseInt(ms)) .option( '-b, --backoff', 'Runs a backoff test on the specified provider', () => config.test = latencyTest) .option( '-c, --concurrency', 'Runs a concurrency test on the specified provider', () => config.test = throughputTest) .option( '-k, --keep-alive', 'Runs a keep-alive test on the specified provider', () => config.test = keepAliveTest) .option( '-i, --iterations <n>', 'Number of times to run the test', n => config.test.iterations = parseInt(n)) .parse(process.argv); config.resultsDir = program.args[0]; if (!fs.existsSync(config.resultsDir)) { fs.mkdirSync(config.resultsDir); } fs.writeFileSync(path.join(config.resultsDir, `${config.provider.name}_${config.test.type}_config.json`), JSON.stringify(config)); let iteration = 0; fs.readdirSync(config.resultsDir).forEach(file => { if (file.match(/[a-z]+_[a-z]+_[0-9]+\.json/) != null) { let left = file.split('.')[0].split('_'); if (left[0] == config.provider.name && left[1] == config.test.type) { let iterationFound = parseInt(left[2]); if (iterationFound >= iteration) { console.log(`Iteration ${iterationFound} already complete`); iteration = iterationFound + 1; } } } }); if (iteration < config.test.iterations) { console.log(`Starting iteration ${iteration}`); slsperf.run(config, false, function processOutput(output) { let outputFile = path.join(config.resultsDir, `${config.provider.name}_${config.test.type}_${iteration}.json`); fs.writeFileSync(outputFile, JSON.stringify(output, null, 4)); console.log(`Finished iteration ${iteration}`); if (++iteration < config.test.iterations) { console.log(`Starting iteration ${iteration}`); slsperf.run(config, true, processOutput); } }); }
version https://git-lfs.github.com/spec/v1 oid sha256:133e8c2e8e43b2523d9ece898741502844fb95bb89c48d1ac90f0901698550ae size 7217
const fs = require('fs') const path = require('path') const paths = require('./paths') // Make sure that including paths.js after env.js will read .env variables. delete require.cache[require.resolve('./paths')] const NODE_ENV = process.env.NODE_ENV if (!NODE_ENV) { throw new Error( 'The NODE_ENV environment variable is required but was not specified.' ) } // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use var dotenvFiles = [ `${paths.dotenv}.${NODE_ENV}.local`, `${paths.dotenv}.${NODE_ENV}`, // Don't include `.env.local` for `test` environment // since normally you expect tests to produce the same // results for everyone NODE_ENV !== 'test' && `${paths.dotenv}.local`, paths.dotenv, ].filter(Boolean) // Load environment variables from .env* files. Suppress warnings using silent // if this file is missing. dotenv will never modify any environment variables // that have already been set. Variable expansion is supported in .env files. // https://github.com/motdotla/dotenv // https://github.com/motdotla/dotenv-expand dotenvFiles.forEach(dotenvFile => { if (fs.existsSync(dotenvFile)) { require('dotenv-expand')( require('dotenv').config({ path: dotenvFile, }) ) } }) // We support resolving modules according to `NODE_PATH`. // This lets you use absolute paths in imports inside large monorepos: // https://github.com/facebookincubator/create-react-app/issues/253. // It works similar to `NODE_PATH` in Node itself: // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. // https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 // We also resolve them to make sure all tools using them work consistently. const appDirectory = fs.realpathSync(process.cwd()) process.env.NODE_PATH = (process.env.NODE_PATH || '') .split(path.delimiter) .filter(folder => folder && !path.isAbsolute(folder)) .map(folder => path.resolve(appDirectory, folder)) .join(path.delimiter) // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be // injected into the application via DefinePlugin in Webpack configuration. const REACT_APP = /^REACT_APP_/i function getClientEnvironment(publicUrl) { const raw = Object.keys(process.env) .filter(key => REACT_APP.test(key)) .reduce( (env, key) => { env[key] = process.env[key] return env }, { // Useful for determining whether we’re running in production mode. // Most importantly, it switches React into the correct mode. NODE_ENV: process.env.NODE_ENV || 'development', // Useful for resolving the correct path to static assets in `public`. // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />. // This should only be used as an escape hatch. Normally you would put // images into the `src` and `import` them in code to get their paths. PUBLIC_URL: publicUrl, } ) // Stringify all values so we can feed into Webpack DefinePlugin const stringified = { 'process.env': Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]) return env }, {}), } return { raw, stringified } } module.exports = getClientEnvironment
import { getMetadataArgsStorage } from "../../index"; import { EventListenerTypes } from "../../metadata/types/EventListenerTypes"; /** * Calls a method on which this decorator is applied before this entity removal. */ export function BeforeRemove() { return function (object, propertyName) { var args = { target: object.constructor, propertyName: propertyName, type: EventListenerTypes.BEFORE_REMOVE }; getMetadataArgsStorage().entityListeners.push(args); }; } //# sourceMappingURL=BeforeRemove.js.map
'use strict'; // Configuring the Articles module angular.module('projects').run(['Menus', function(Menus) { // Set top bar menu items //Menus.addMenuItem('topbar', 'Projects', 'projects', 'dropdown', '/projects(/create)?'); //Menus.addSubMenuItem('topbar', 'projects', 'List Projects', 'projects'); //Menus.addSubMenuItem('topbar', 'projects', 'New Project', 'projects/create'); } ]);
var request = require('request'); request.post({ url: 'http://127.0.0.1:3000/tag/add', form: { description: '添加一个更新style的参数的tag5', //color: 'red', //'background-color': 'yellow', //icon: 'http://www.fsy0718.com/1.png', 'font-size': '14px' } }, function(err, res, body) { //console.log(res); console.log(body); }); request.put({ url: 'http://127.0.0.1:3000/tag/update', form: { description: '更新tag1', color: 'yellow', //color: null, //icon: 'http://fsy0718', //icon: null, //'background-color': 'yellow', //'background-color': null, uid: '571f005c7eb763f81d035211', style: null } }, function(err, res, body) { console.log(body); }); request.delete({ url: 'http://127.0.0.1:3000/tag/delete', form: { uid: '571effff7eb763f81d03520e' } }, function(err, res, body) { //console.log(err); console.log(res.statusCode); console.log(body); //console.log(body); })
var nofactor = require("nofactor"); var defaults = require("./defaults"); var template = require("./template"); var parser = require("./parser"); template.parser = parser; var paperclip = module.exports = { /** */ accessors: defaults.accessors, /** */ runloop: defaults.runloop, /** */ document: nofactor, /** * web component base class */ Component : require("./components/base"), /** */ Attribute : require("./attributes/script"), /** * template factory */ template : template, /** */ components : defaults.components, /** */ attributes : defaults.attributes, /** */ modifiers: defaults.modifiers, /** */ parse: parser.parse }; /* istanbul ignore next */ if (typeof window !== "undefined") { window.paperclip = paperclip; // no conflict mode. Release paperclip from global scope. window.paperclip.noConflict = function() { delete window.paperclip; return paperclip; }; }
/** * The Mining layer module. * * @return MiningLayer class (extends CartoDBLayerClass) */ define(['abstract/layer/CartoDBLayerClass'], function(CartoDBLayerClass) { 'use strict'; var KhmMiningLayer = CartoDBLayerClass.extend({ options: { sql: "SELECT '{tableName}' as tablename, cartodb_id, the_geom_webmercator, area_name as name, round((shape_area::float)/10000) as area_ha,min_name as company, commodity as type, '{tableName}' AS layer, {analysis} AS analysis FROM {tableName}", infowindow: true, interactivity: 'cartodb_id, tablename, name, company, type, area_ha, analysis', analysis: true } }); return KhmMiningLayer; });
define(['angularAMD'], function(angularAMD){ 'use strict'; angularAMD.service('ManageService', function($q, $http){ var manageService = {}; var roles = []; manageService.permissions = []; manageService.savePermission = function(perm){ console.info('savePermission',perm); var d = $q.defer(); if(perm.id){ var t = []; angular.forEach(manageService.permissions,function(p){ if(p.id = perm.id){ t.push(perm); }else{ t.push(p); } }); manageService.permissions = t; d.resolve(manageService.permissions); }else{ if(perm.name == 'abc'){ d.reject('save failed:name aready exist'); }else{ manageService.permissions.push(perm); d.resolve(permissions); } } return d.promise; }; manageService.getPermissions = function(){ var d = $q.defer(); // /permissions // setTimeout(function(){ // $http.get( 'api/permission.json?_=' + (new Date()).getTime() ) // .success(function(data){ // manageService.permissions = data; // d.resolve(data); // }); // },2000); $http.get('http://api.oms.com/admin/pers') .success(function(data){ manageService.permissions = data. d.resolve(data); }); return d.promise; } manageService.deletePermission = function(id){ var d = $q.defer(); var t = []; angular.forEach(manageService.permissions,function(p){ if(p.id != id){ t.push(p); } }); manageService.permissions = t; setTimeout(function(){ d.resolve(manageService.permissions); // d.reject('fail test'); },2000); return d.promise; } return manageService; }); });
var Marionette = require('backbone.marionette'), Backbone = require('backbone'), $ = require('jquery'), Radio = require('backbone.radio'), Route = require('./route'); module.exports = Marionette.AppRouter.extend({ constructor: function() { this.channel = Radio.channel('router'); this.on('all', this._onRouterEvent); this.listenTo(Backbone.history, 'route', this._onHistoryRoute); Marionette.AppRouter.apply(this, arguments); }, _onRouterEvent: function(name, args) { this.channel.trigger(name, this, args); }, _onHistoryRoute: function(router) { if(this === router) { this.active = true; } else { this.active = false; } }, execute: function(callback, args) { var that = this; if(!this.active) { this.triggerMethod('before:enter', args); } this.triggerMethod('before:route', args); $.when(this._execute(callback, args)).then(function() { if(!this.active) { that.triggerMethod('enter', args); } that.triggerMethod('route', args); }); }, _execute: function(callback, args) { var route = callback.apply(this, args); if(route instanceof Route) { route.router = this; return route.enter(args); } }, triggerMethod: Marionette.triggerMethod });
'use strict'; // user-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. //import mongoose const mongoose = require('mongoose'); //get schema from mongoose const Schema = mongoose.Schema; //create schema object const userSchema = new Schema({ username: { type: String, required: true, unique: true }, password: { type: String, require: true }, roles: [{ type: String, required: true }], createdAt: { type: Date, 'default': Date.now }, updatedAt: { type: Date, 'default': Date.now } }); //set the schema for this collection const userModel = mongoose.model('user', userSchema); //export for use elsewhere module.exports = userModel;
'use strict'; var http = require('http'); var serveStatic = require('serve-static'); var serve = serveStatic('public'); var minimist = require('minimist'); var request = require('request'); var qs = require('querystring'); var moment = require('moment'); var argv = minimist(process.argv); var endpointUrl = 'http://earthquake.usgs.gov/fdsnws/event/1/query'; var reqQuerystring; var ISO_FORMAT = 'YYYY-MM-DD'; var requestHandler = function(req, res) { if (req.url.indexOf('/data') !== -1) { // parsear querystring de req.url utilizando el módulo qs // la querystring comienza luego del '?' de la URL // utilizar el módulo request para hacer una solicitud GET a // endpointUrl con un querystring con los valores // {format: 'geojson', starttime: 'el valor de starttime en req.url', endtime: 'el valor de endtime en req.url'} // si la solicitud respondió ok, escribir el status code 200 en req y agregar el header de Content-Type // en 'application/json' // luego terminar req con el resultado de invocar mapToObjects(aggregate(body)) dónde body es la respuesta // de la solicitud realizada //si hubo un error, responder con un status code 400 y terminar req sin datos return; } // parte dónde sirvo contenido estático serve(req, res, function() { res.end(); }); } var server = http.createServer(requestHandler); var port = argv.port || process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8000; var ip = argv.ip || process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'; server.listen(port, ip, function() { console.log('Server is now listening at port: ' + port); }); function aggregate(arr) { var resultado = {}; arr.features.forEach(function(elem) { var pais = elem.properties.place.split(',')[1]; if (resultado[pais]) { resultado[pais]++; } else { resultado[pais] = 1; } }); return resultado; } function mapToObjects(obj) { var resultado = []; var keys = Object.keys(obj); keys.forEach(function(key) { resultado.push({ name: key, value: obj[key]}); }); return resultado; }
var MongoClient = require('mongodb').MongoClient; var assert = require('assert'); var ObjectId = require('mongodb').ObjectID; var url = 'mongodb://localhost:27017/test'; var findRestaurants = function(db, callback) { var cursor = db.collection('restaurants').find( // { "borough": "Manhattan" } // {"address.zipcode": "10075"} // { "grades.grade": "B" } // { "grades.score": { $gt: 30 } } // { "grades.score": { $lt: 10 } } // { "cuisine": "Italian", "address.zipcode": "10075" } // conjunction (AND) { $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ] } // disjunction (OR) ).sort( { "borough": 1, "address.zipcode": 1 } ); cursor.each(function(err, doc) { assert.equal(err, null); if (doc != null) { console.dir(doc); } else { callback(); } }); }; MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to server."); findRestaurants(db, function() { db.close(); }); });
// // Track when `Buy` is clicked in main nav. // (function (ga) { document.getElementById('buy').addEventListener('click', function () { ga('send', 'event', 'Nav', 'buy', window.location.pathname); }); })(ga);
// AdminLTE Gruntfile module.exports = function (grunt) { 'use strict'; grunt.initConfig({ watch: { // If any .less file changes in directory "build/less/" run the "less"-task. files: ["build/less/*.less", "build/less/skins/*.less", "dist/js/app.js"], tasks: ["less", "uglify"] }, // "less"-task configuration // This task will compile all less files upon saving to create both AdminLTE.css and AdminLTE.min.css less: { // Development not compressed development: { options: { // Whether to compress or not compress: false }, files: { // compilation.css : source.less "dist/css/AdminLTE.css": "build/less/AdminLTE.less", //Non minified skin files "dist/css/skins/skin-blue.css": "build/less/skins/skin-blue.less", "dist/css/skins/skin-black.css": "build/less/skins/skin-black.less", "dist/css/skins/skin-yellow.css": "build/less/skins/skin-yellow.less", "dist/css/skins/skin-green.css": "build/less/skins/skin-green.less", "dist/css/skins/skin-red.css": "build/less/skins/skin-red.less", "dist/css/skins/skin-purple.css": "build/less/skins/skin-purple.less", "dist/css/skins/skin-blue-light.css": "build/less/skins/skin-blue-light.less", "dist/css/skins/skin-black-light.css": "build/less/skins/skin-black-light.less", "dist/css/skins/skin-yellow-light.css": "build/less/skins/skin-yellow-light.less", "dist/css/skins/skin-green-light.css": "build/less/skins/skin-green-light.less", "dist/css/skins/skin-red-light.css": "build/less/skins/skin-red-light.less", "dist/css/skins/skin-purple-light.css": "build/less/skins/skin-purple-light.less", "dist/css/skins/_all-skins.css": "build/less/skins/_all-skins.less" } }, // Production compresses version production: { options: { // Whether to compress or not compress: true }, files: { // compilation.css : source.less "dist/css/AdminLTE.min.css": "build/less/AdminLTE.less", // Skins minified "dist/css/skins/skin-blue.min.css": "build/less/skins/skin-blue.less", "dist/css/skins/skin-black.min.css": "build/less/skins/skin-black.less", "dist/css/skins/skin-yellow.min.css": "build/less/skins/skin-yellow.less", "dist/css/skins/skin-green.min.css": "build/less/skins/skin-green.less", "dist/css/skins/skin-red.min.css": "build/less/skins/skin-red.less", "dist/css/skins/skin-purple.min.css": "build/less/skins/skin-purple.less", "dist/css/skins/skin-blue-light.min.css": "build/less/skins/skin-blue-light.less", "dist/css/skins/skin-black-light.min.css": "build/less/skins/skin-black-light.less", "dist/css/skins/skin-yellow-light.min.css": "build/less/skins/skin-yellow-light.less", "dist/css/skins/skin-green-light.min.css": "build/less/skins/skin-green-light.less", "dist/css/skins/skin-red-light.min.css": "build/less/skins/skin-red-light.less", "dist/css/skins/skin-purple-light.min.css": "build/less/skins/skin-purple-light.less", "dist/css/skins/_all-skins.min.css": "build/less/skins/_all-skins.less" } } }, // Uglify task info. Compress the js files. uglify: { options: { mangle: true, preserveComments: 'some' }, my_target: { files: { 'dist/js/app.min.js': ['dist/js/app.js'] } } }, // Build the documentation files includes: { build: { src: ['*.html'], // Source files dest: 'documentation/', // Destination directory flatten: true, cwd: 'documentation/build', options: { silent: true, includePath: 'documentation/build/include' } } }, // Optimize images image: { dynamic: { files: [{ expand: true, cwd: 'build/img/', src: ['**/*.{png,jpg,gif,svg,jpeg}'], dest: 'dist/img/' }] } }, // Validate JS code jshint: { options: { jshintrc: '.jshintrc' }, core: { src: 'dist/js/app.js' }, demo: { src: 'dist/js/demo.js' }, pages: { src: 'dist/js/pages/*.js' } }, // Validate CSS files csslint: { options: { csslintrc: 'build/less/.csslintrc' }, dist: [ 'dist/css/AdminLTE.css', ] }, // Validate Bootstrap HTML bootlint: { options: { relaxerror: ['W005'] }, files: ['pages/**/*.html', '*.html'] }, // Delete images in build directory // After compressing the images in the build/img dir, there is no need // for them clean: { build: ["build/img/*"] } }); // Load all grunt tasks // LESS Compiler grunt.loadNpmTasks('grunt-contrib-less'); // Watch File Changes grunt.loadNpmTasks('grunt-contrib-watch'); // Compress JS Files grunt.loadNpmTasks('grunt-contrib-uglify'); // Include Files Within HTML grunt.loadNpmTasks('grunt-includes'); // Optimize images grunt.loadNpmTasks('grunt-image'); // Validate JS code grunt.loadNpmTasks('grunt-contrib-jshint'); // Delete not needed files grunt.loadNpmTasks('grunt-contrib-clean'); // Lint CSS grunt.loadNpmTasks('grunt-contrib-csslint'); // Lint Bootstrap grunt.loadNpmTasks('grunt-bootlint'); // Linting task grunt.registerTask('lint', ['jshint', 'csslint', 'bootlint']); // The default task (running "grunt" in console) is "watch" grunt.registerTask('default', ['watch']); };
const config = require('./config') const describeTasks = require('./tasks') module.exports = api => { describeTasks(api) api.describeConfig(config) }
import React from 'react' import ReactDOM from 'react-dom' import App from './components/App.jsx' ReactDOM.render( <App />, document.getElementById('root') )
import React from 'react'; import GitHubFork from './GitHubFork'; import { Row, Col } from 'react-bootstrap'; class Header extends React.Component { render() { return ( <div> <GitHubFork /> <header className="header"> <Row> <Col md={6} mdOffset={3}> <h1 className="neon">The <div className="blink">Beer</div> Store</h1> </Col> </Row> </header> </div> ); } } export default Header;
class TestFailure extends Error { constructor(message) { super(message) this.name = this.constructor.name Error.captureStackTrace(this, this.constructor) } } module.exports = TestFailure
// **Useful functions that can be shared across modules** define(['utils/mixins'], function(mixins) { function extend (target, source, use_clone, not_override) { var use_clone = (typeof use_clone === "undefined") ? true : use_clone, target_clone = use_clone ? clone(target): target; for(prop in source) { if (not_override) { target_clone[prop] = target_clone[prop] ? target_clone[prop] : source[prop]; } else { target_clone[prop] = source[prop]; } } return target_clone; } mixins.call(extend.prototype); return extend; });
import Player from './player.js'; // A player whose moves are not determined through local user interaction, but // rather, by a asynchronous getNextMove method that AsyncPlayer subclasses // define class AsyncPlayer extends Player { // Wait for a short moment to give the user time to see and process the // player's actions; all AsyncPlayer subclasses must define a waitDelay as a // static property on the class object wait(callback) { setTimeout(callback, this.waitDelay); } // Return a promise that resolves with a { column } object containing the // integer column in which to place the player's next chip; all AsyncPlayer // subclasses must implement this method getNextMove() { throw new Error('This method must be implemented by a subclass of AsyncPlayer'); } } // Each AsyncPlayer subclass should override this type property with a string // value unique to that subclass AsyncPlayer.prototype.type = 'async'; export default AsyncPlayer;
import React, {Component} from 'react'; import {connect} from 'react-redux'; import ImageDetail from '../../components/images/image-detail'; import {goTo} from '../../modules/navigation/actions'; import {getActiveData, isActiveLoaded} from '../../modules/images/selectors'; import {fetchDetail} from '../../modules/images/actions'; class Container extends Component { componentDidMount() { const {params, load} = this.props; load(); window.onkeyup = key => { let code = key.keyCode ? key.keyCode : key.which; switch (code) { case 39: console.log('Next'); break; case 37: console.log('Prev'); break; } }; } render() { return <ImageDetail {...this.props} />; } } function mapStateToProps(state) { return { image: getActiveData(state), loaded: isActiveLoaded(state) }; } const mapDispatchToProps = (dispatch, ownProps) => { return { load() { dispatch(fetchDetail(ownProps.params.id)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(Container);
Function.bind || (Function.prototype.bind = new function () { function newApply(Constructor, args) { var argNames = [], len = args.length, i = 0; while (i < len) { argNames.push('arg' + i); i++; } argNames = argNames.join(','); return new Function( 'Constructor', argNames, 'return new Constructor(' + argNames + ')' ).apply(window, [Constructor].concat(args)); } return function (boundThis) { var boundArgs = Array.slice(arguments, 1), targetFunc = this; function boundFunc() { var proto, args, len; function NOP() {} if (boundFunc._protoMagic) { boundFunc._protoMagic = false; NOP.prototype = this; NOP.prototype.constructor = targetFunc; return new NOP; } else { args = boundArgs.concat(Array.from(arguments)); len = args.length; } if (this instanceof boundFunc) { boundFunc._protoMagic = true; switch (len) { case 0: proto = new targetFunc; break; case 1: proto = new targetFunc(args[0]); break; case 2: proto = new targetFunc(args[0], args[1]); break; default: proto = newApply(targetFunc, args); } NOP.prototype = proto; boundFunc.prototype = new NOP; boundFunc.prototype.constructor = boundFunc; return new boundFunc; } switch (len) { case 0: return targetFunc.call(boundThis); case 1: return targetFunc.call(boundThis, args[0]); case 2: return targetFunc.call(boundThis, args[0], args[1]); } return targetFunc.apply(boundThis, args); } if ('function' != typeof targetFunc) { throw new TypeError('Function.prototype.bind ' + 'called on non-function'); } boundFunc._protoMagic = false; return boundFunc; }; });