text
stringlengths
2
6.14k
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Card from './../atoms/Card'; class ElectionReminderPrompt extends Component { render() { return ( <Card title="Election Day Reminder" className="prompt-card" actions={[ <button key="1" className="primary">Sure</button>, <button key="2" onClick={this.props.onClose}>No Thanks</button> ]}> Would you like us to email or text you these results on election day? </Card> ); } } ElectionReminderPrompt.propTypes = { onClose: PropTypes.func }; module.exports = ElectionReminderPrompt;
define(['exports', 'aurelia-metadata'], function (exports, _aureliaMetadata) { 'use strict'; exports.__esModule = true; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); exports.ensure = ensure; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationMetadata = (function () { function ValidationMetadata() { _classCallCheck(this, ValidationMetadata); this.properties = []; } ValidationMetadata.prototype.getOrCreateProperty = function getOrCreateProperty(propertyName) { var property = this.properties.find(function (x) { return x.propertyName === propertyName; }); if (property === undefined) { property = new ValidationPropertyMetadata(propertyName); this.properties.push(property); } return property; }; ValidationMetadata.prototype.setup = function setup(validation) { this.properties.forEach(function (property) { property.setup(validation); }); }; _createClass(ValidationMetadata, null, [{ key: 'metadataKey', value: 'aurelia:validation', enumerable: true }]); return ValidationMetadata; })(); exports.ValidationMetadata = ValidationMetadata; var ValidationPropertyMetadata = (function () { function ValidationPropertyMetadata(propertyName) { _classCallCheck(this, ValidationPropertyMetadata); this.propertyName = propertyName; this.setupSteps = []; } ValidationPropertyMetadata.prototype.addSetupStep = function addSetupStep(setupStep) { this.setupSteps.push(setupStep); }; ValidationPropertyMetadata.prototype.setup = function setup(validation) { validation.ensure(this.propertyName); this.setupSteps.forEach(function (setupStep) { setupStep(validation); }); }; return ValidationPropertyMetadata; })(); function ensure(setupStep) { return function (target, propertyName) { var validationMetadata = _aureliaMetadata.metadata.getOrCreateOwn(ValidationMetadata.metadataKey, ValidationMetadata, target); var property = validationMetadata.getOrCreateProperty(propertyName); property.addSetupStep(setupStep); }; } });
#!/usr/bin/env babel-node require('./helper') let fs = require('fs').promise let path = require('path') let argv = require('yargs').argv let prom = require('songbird') async function ls(dirPath) { let stat = await fs.stat(dirPath) if (!stat.isDirectory()) return [dirPath] let promises = [] let merged = [] let listItem = await fs.readdir(dirPath) for (let item of listItem ) { if (argv.R) { let promise = ls(path.join(dirPath, item)) promises.push(promise) } else { merged.push(path.join(dirPath, item)) } } if (argv.R) { let files = await prom.all(promises) merged = [].concat.apply([], files) } return merged } async function main() { let input = process.argv[2] || __dirname console.log(await ls(input)) } main() /*async function ls(dirName) { // console.log('1' + dirName); let fileStat = await fs.stat(dirName) if (!fileStat.isDirectory()) { console.log('2' + dirName) } let promise = fs.readdir(dirName) let fileNames = await fs.readdir(dir) // Your implementation here let lsPromises = [] console.log('4' + fileNames) for (let fileName in fileNames) { let filePath = path.join(dir, fileNames[fileName]) // TODO: Obtain the stat promise from fs.stat(filePath) console.log('3' + filePath) // TODO: Use stat.isDirectory to exclude subdirectories // ... let fileStat = await fs.stat(filePath) if (fileStat.isDirectory()) { const promise = ls(filePath) lsPromises.push(promise) } process.stdout.write(filePath, '\n') } } async function main() { await ls(dir) } main()*/
var Rec2 = require('rec2') var tile = require('../tile') var page = new Rec2(0, 0, 100, 100) function rand() { return Math.random() * 100 } var contents = [ new Rec2(rand(),rand(),rand(),rand()), new Rec2(rand(),rand(),rand(),rand()), new Rec2(rand(),rand(),rand(),rand()), new Rec2(rand(),rand(),rand(),rand()), new Rec2(rand(),rand(),rand(),rand()) ] console.log(tile(contents, page)) var grid = require('../grid') var contents = [ new Rec2(rand(),rand(),rand(),rand()), new Rec2(rand(),rand(),rand(),rand()), new Rec2(rand(),rand(),rand(),rand()), new Rec2(rand(),rand(),rand(),rand()), new Rec2(rand(),rand(),rand(),rand()) ] console.log(grid(contents, page))
// Copyright (c) Microsoft Corporation. All rights reserved. // This code is licensed by Microsoft Corporation under the terms // of the MICROSOFT REACTIVE EXTENSIONS FOR JAVASCRIPT AND .NET LIBRARIES License. // See http://go.microsoft.com/fwlink/?LinkId=186234. (function() { var fromMooToolsEvent = Rx.Observable.FromMooToolsEvent = function(mooToolsObject, eventType) { return Rx.Observable.Create(function(observer) { var handler = function(eventObject) { observer.OnNext(eventObject); }; var handle = mooToolsObject.addEvent(eventType, handler); return function() { mooToolsObject.removeEvent(eventType, handler); }; }); }; })();
import AWS from 'aws-sdk'; import https from 'https'; import url from 'url'; exports.handler = (event, context) => { console.log("REQUEST RECEIVED:\n" + JSON.stringify(event)); // For Delete requests, immediately send a SUCCESS response. if (event.RequestType == "Delete") { sendResponse(event, context, "SUCCESS"); return; } let stackName = event.ResourceProperties.StackName; let responseStatus = "FAILED"; let responseData = {}; if (stackName) { let cfn = new AWS.CloudFormation(); cfn.describeStacks({StackName: stackName}).promise() .then(data => { console.log('SUCCESSFULLY DESCRIBED STACK'); data.Stacks[0].Outputs.forEach(function (output) { responseData[output.OutputKey] = output.OutputValue; }); responseStatus = "SUCCESS"; sendResponse(event, context, responseStatus, responseData); }) .catch(err => { console.log('FAILED TO DESCRIBE STACK:', err); sendResponse(event, context, responseStatus, responseData); }); } }; // Send response to the pre-signed S3 URL function sendResponse(event, context, responseStatus, responseData) { var responseBody = JSON.stringify({ Status: responseStatus, Reason: "See the details in CloudWatch Log Stream: " + context.logStreamName, PhysicalResourceId: context.logStreamName, StackId: event.StackId, RequestId: event.RequestId, LogicalResourceId: event.LogicalResourceId, Data: responseData }); console.log("RESPONSE BODY:\n", responseBody); var parsedUrl = url.parse(event.ResponseURL); var options = { hostname: parsedUrl.hostname, port: 443, path: parsedUrl.path, method: "PUT", headers: { "content-type": "", "content-length": responseBody.length } }; console.log("SENDING RESPONSE...\n"); var request = https.request(options, function (response) { console.log("STATUS: " + response.statusCode); console.log("HEADERS: " + JSON.stringify(response.headers)); // Tell AWS Lambda that the function execution is done context.done(); }); request.on("error", function (error) { console.log("sendResponse Error:" + error); // Tell AWS Lambda that the function execution is done context.done(); }); // write data to request body request.write(responseBody); request.end(); }
const fs = require('fs') const path = require('path') const { spawn } = require('child_process') const { deepStrictEqual } = require('assert') const devnull = require('dev-null') const { SubtitleParser, SubtitleStream } = require('..') const repo = 'https://github.com/Matroska-Org/matroska-test-files.git' const testFile = path.resolve(__dirname, 'matroska-test-files/test_files/test5.mkv') if (!fs.existsSync(testFile)) { console.log(`Did not find ${testFile}, downloading from git repository.`) const git = spawn('git', ['clone', repo, '--depth', '1'], { cwd: __dirname, stdio: ['ignore', 'inherit', 'inherit'] }) git.on('close', (code) => { if (code === 0) { tests() } else { console.error(`git clone process exited with code ${code}`) process.exit(1) } }) } else { tests() } function tests () { console.log('Running mkv tests...') testBasic() testSeeking() } function testBasic () { const parser = new SubtitleParser() parser.once('tracks', (tracks) => deepStrictEqual(tracks, [ { number: 3, language: undefined, type: 'utf8' }, { number: 4, language: 'hun', type: 'utf8' }, { number: 5, language: 'ger', type: 'utf8' }, { number: 6, language: 'fre', type: 'utf8' }, { number: 8, language: 'spa', type: 'utf8' }, { number: 9, language: 'ita', type: 'utf8' }, { number: 11, language: 'jpn', type: 'utf8' }, { number: 7, language: 'und', type: 'utf8' } ])) const subtitles = {} parser.on('subtitle', (subtitle, trackNumber) => { if (!subtitles[trackNumber]) subtitles[trackNumber] = [] subtitles[trackNumber].push(subtitle) }) parser.on('finish', () => { const expected = { 3: [ { text: '...the colossus of Rhodes!', time: 3549, duration: 1741 }, { text: 'No!', time: 5757, duration: 921 }, { text: 'The colossus of Rhodes\r\nand it is here just for you Proog.', time: 6715, duration: 5829 }, { text: 'It is there...', time: 41626, duration: 1922 }, { text: "I'm telling you,\r\nEmo...", time: 43584, duration: 3081 } ], 4: [ { text: 'A jobb oldaladon láthatod...\r\n...tudod mit...', time: 42, duration: 3375 }, { text: '...a Rodoszi Kolosszust!', time: 3625, duration: 1750 }, { text: 'Ne!', time: 6458, duration: 875 }, { text: 'A Rodoszi Kolosszust\r\nés csak neked van itt Proog.', time: 7375, duration: 5417 }, { text: 'Ott van...', time: 41958, duration: 1834 }, { text: 'Én mondom neked,\r\nEmo...', time: 43833, duration: 2292 } ], 5: [ { text: 'Auf der rechten Seite sieht man...|...rate mal...', time: 42, duration: 3375 }, { text: '...den Koloss von Rhodos!', time: 3625, duration: 1750 }, { text: 'Nein!', time: 6458, duration: 875 }, { text: 'Den Koloss von Rhodos|und er ist nur für dich hier, Proog.', time: 7375, duration: 5417 }, { text: 'Es ist da...', time: 41958, duration: 1834 }, { text: 'Wenn ich es dir doch sage,|Emo...', time: 43833, duration: 2292 } ], 6: [ { text: 'À votre droite vous pouvez voir...|Ça alors...', time: 42, duration: 3375 }, { text: '... le colosse de Rhodes !', time: 3625, duration: 1750 }, { text: 'Non !', time: 6375, duration: 750 }, { text: "Le colosse de Rhodes,|et il n'est là que pour toi Proog.", time: 7375, duration: 5000 }, { text: 'Mais c’est là...', time: 41958, duration: 1500 }, { text: 'Je te le jure,|Emo...', time: 43833, duration: 2292 } ], 7: [ { text: 'å', time: 42, duration: 3375 }, { text: '…ロードス島ã', time: 3625, duration: 1750 }, { text: 'ã‚„ã‚', time: 6458, duration: 875 }, { text: 'ã', time: 7375, duration: 5417 }, { text: 'ã', time: 41958, duration: 1834 }, { text: 'ã', time: 43833, duration: 2292 } ], 8: [ { text: 'A tu derecha puedes ver...|adivina qué...', time: 42, duration: 3375 }, { text: '...¡El Coloso de Rodas!', time: 3625, duration: 1750 }, { text: '¡No!', time: 6458, duration: 875 }, { text: 'El Coloso de Rodas |y está aquí sólo para ti, Proog.', time: 7375, duration: 5417 }, { text: 'Está ahí...', time: 41958, duration: 1834 }, { text: 'Te lo estoy diciendo,|Emo...', time: 43833, duration: 2292 } ], 9: [ { text: 'Alla tua destra puoi vedere...|...ma pensa...', time: 42, duration: 3375 }, { text: '...Il colosso di Rodi!', time: 3625, duration: 1750 }, { text: 'No!', time: 6458, duration: 875 }, { text: 'Il colosso di Rodi|ed è qui solo per te Proog.', time: 7375, duration: 5417 }, { text: 'È lì...', time: 41958, duration: 1834 }, { text: 'Te lo stavo dicendo,|Emo...', time: 43833, duration: 2292 } ], 11: [ { text: '右にあるのは…|…すごい!…', time: 42, duration: 3375 }, { text: '…ロードス島の巨像だ!', time: 3625, duration: 1750 }, { text: 'やめろ!', time: 6458, duration: 875 }, { text: 'この巨像はあなたの物|プルーグ、あなたのだよ', time: 7375, duration: 5417 }, { text: 'いってるじゃないか…', time: 41958, duration: 1834 }, { text: 'そこにあるって、イーモ…', time: 43833, duration: 2292 } ] } for (const key of Object.keys(expected)) { deepStrictEqual(subtitles[key], expected[key]) } }) fs.createReadStream(testFile).pipe(parser) } function testSeeking () { let subtitleStream = new SubtitleStream() subtitleStream.once('tracks', (tracks) => { subtitleStream = new SubtitleStream(subtitleStream) subtitleStream.on('subtitle', (subtitle, trackNumber) => { deepStrictEqual(subtitle.time, trackNumber === 3 ? 43584 : 43833) }) fs.createReadStream(null, { fd: filestream.fd, start: 30000000 }).pipe(subtitleStream).pipe(devnull()) }) const filestream = fs.createReadStream(testFile) filestream.pipe(subtitleStream).pipe(devnull()) }
'use strict'; let path = require('path'); let gulp = require('gulp'); let conf = require('./conf'); let browserSync = require('browser-sync'); function isOnlyChange(event) { return event.type === 'changed'; } gulp.task('watch', ['scripts:watch', 'inject'], function () { gulp.watch([path.join(conf.paths.src, '/*.html'), 'bower.json'], ['inject']); gulp.watch([ path.join(conf.paths.src, '/app/styles/*.css'), path.join(conf.paths.src, '/app/styles/*.scss') ], function (event) { if (isOnlyChange(event)) { gulp.start('styles'); } else { gulp.start('inject'); } }); });
var _ = require('underscore'); module.exports = { priority: 1, loadConfig: function(context, next, complete) { var modules = context.config.attributes.modules, errored; _.each(context.libraries.configs, function(library) { // Import any modules that are not overriden in the core file _.each(library.modules, function(module, key) { if (!_.has(modules, key)) { module = modules[key] = _.clone(module); ['scripts', 'styles', 'static', 'routes'].forEach(function(field) { var value = module[field]; // Deep(er) clone, updating file references if (_.isArray(value)) { module[field] = context.libraries.mapFiles(value, library); } else if (value) { module[field] = _.clone(value); } }); } }); }); _.each(modules, function(module, name) { module.name = module.name || name; var mixins; try { mixins = context.libraries.moduleMixins(module); } catch (err) { errored = true; return complete(new Error('Failed mixins for module "' + name + '": ' + err.message)); } // Map existing files that have mixin references try { ['scripts', 'styles', 'static'].forEach(function(field) { var list = module[field]; if (list) { module[field] = context.libraries.mapFiles(list); } }); _.each(mixins, function(mixin) { var mixinConfig = mixin.mixinConfig, library = mixin.library; // Direct copy for any fields that are not already defined on the object. _.defaults(module, library.attributes); // Merge known array/object types ['scripts', 'styles', 'static', 'routes'].forEach(function(field) { mergeValues(module, field, library, mixinConfig, context); }); }); } catch (err) { errored = true; return complete(err); } }); // Remove suppressed modules completely _.each(_.keys(modules), function(name) { if (!modules[name]) { delete modules[name]; } }); if (!errored) { next(complete); } } }; function firstLocal(collection) { for (var i = 0, len = collection.length; i < len; i++) { if (!collection[i].global) { return i; } } return i; } function mergeValues(module, field, library, mixinConfig, context) { var value = module[field], mixinValue = library.attributes[field]; if (!value) { return; } if (value === mixinValue) { // Clone any direct copy entries from a mixin if (_.isArray(value)) { module[field] = context.libraries.mapFiles(value, library, mixinConfig); } else { module[field] = _.clone(value); } } else if (!_.isArray(value)) { _.defaults(value, mixinValue); } else if (mixinValue) { mixinValue = context.libraries.mapFiles(mixinValue, library, mixinConfig); var mixinFirstLocal = firstLocal(mixinValue), moduleFirstLocal = firstLocal(value); if (mixinFirstLocal) { value.unshift.apply(value, mixinValue.slice(0, mixinFirstLocal)); } if (mixinFirstLocal < mixinValue.length) { var locals = mixinValue.slice(mixinFirstLocal); locals.unshift(mixinFirstLocal + moduleFirstLocal, 0); value.splice.apply(value, locals); } } }
Pseudohelp = { init: function(){ jQuery('.pseudo-container section > div:first').toggleClass('visible'); var type_links = jQuery('.pseudo-container header a'); type_links.click(function(e){ e.preventDefault(); type = jQuery(this).text(); jQuery('.pseudo-container section > div').removeClass('visible'); jQuery('.pseudo-container div.'+type).addClass('visible'); }); var tables = jQuery('.pseudo-container table'); jQuery('.pseudo-help-filter').keyup(function() { jQuery.uiTableFilter( tables, this.value ); }); var links_to_help = jQuery('a[href="#pseudo-help"]') links_to_help.click(function(e){ e.preventDefault(); Pseudohelp.toggle(); }); }, toggle: function(){ jQuery('html').toggleClass('pseudohelp-visible') } } jQuery(function() { Pseudohelp.init(); }); /* * Copyright (c) 2008 Greg Weber greg at gregweber.info * Dual licensed under the MIT and GPLv2 licenses just as jQuery is: * http://jquery.org/license * * documentation at http://gregweber.info/projects/uitablefilter * * allows table rows to be filtered (made invisible) * <code> * t = $('table') * $.uiTableFilter( t, phrase ) * </code> * arguments: * jQuery object containing table rows * phrase to search for * optional arguments: * column to limit search too (the column title in the table header) * ifHidden - callback to execute if one or more elements was hidden */ (function($) { $.uiTableFilter = function(jq, phrase, column, ifHidden){ var new_hidden = false; if( this.last_phrase === phrase ) return false; var phrase_length = phrase.length; var words = phrase.toLowerCase().split(" "); // these function pointers may change var matches = function(elem) { elem.show() } var noMatch = function(elem) { elem.hide(); new_hidden = true } var getText = function(elem) { return elem.text() } if( column ) { var index = null; jq.find("thead > tr:last > th").each( function(i){ if( $.trim($(this).text()) == column ){ index = i; return false; } }); if( index == null ) throw("given column: " + column + " not found") getText = function(elem){ return $(elem.find( ("td:eq(" + index + ")") )).text() } } // if added one letter to last time, // just check newest word and only need to hide if( (words.size > 1) && (phrase.substr(0, phrase_length - 1) === this.last_phrase) ) { if( phrase[-1] === " " ) { this.last_phrase = phrase; return false; } var words = words[-1]; // just search for the newest word // only hide visible rows matches = function(elem) {;} var elems = jq.find("tbody:first > tr:visible") } else { new_hidden = true; var elems = jq.find("tbody:first > tr") } elems.each(function(){ var elem = $(this); $.uiTableFilter.has_words( getText(elem), words, false ) ? matches(elem) : noMatch(elem); }); last_phrase = phrase; if( ifHidden && new_hidden ) ifHidden(); return jq; }; // caching for speedup $.uiTableFilter.last_phrase = "" // not jQuery dependent // "" [""] -> Boolean // "" [""] Boolean -> Boolean $.uiTableFilter.has_words = function( str, words, caseSensitive ) { var text = caseSensitive ? str : str.toLowerCase(); for (var i=0; i < words.length; i++) { if (text.indexOf(words[i]) === -1) return false; } return true; } }) (jQuery);
import Ember from 'ember'; import SessionGuestMixin from '../../../mixins/session-guest'; import { module, test } from 'qunit'; module('SessionGuestMixin'); // Replace this with your real tests. test('it works', function(assert) { var SessionGuestObject = Ember.Object.extend(SessionGuestMixin); var subject = SessionGuestObject.create(); assert.ok(subject); });
var Lab = require('lab'); var Code = require('code'); var lab = exports.lab = Lab.script(); var io = require('socket.io-client'); var spawn = require('child_process').spawn; var request = require('request'); var experiment = lab.experiment; var test = lab.test; var before = lab.before; var after = lab.after; var expect = Code.expect; experiment(':', function() { var server; var c1Io; var c2Io; var c1Id; var c2Id; var c1FingerTable = {}; var c2FingerTable = {}; var ioOptions = { transports: ['websocket'], 'force new connection': true }; var url = 'http://localhost:9000'; before(function(done) { server = spawn('node', ['./src/index.js']); server.stdout.on('data', function(data) { console.log('\n stdout: ' + data); }); server.stderr.on('data', function(data) { console.log('\n stderr: ' + data); }); setTimeout(function() { done(); }, 1000); }); after(function(done) { c1Io.disconnect(); c2Io.disconnect(); setTimeout(function() { server.on('close', function(code) { console.log('exited: ' + code); }); server.kill(); }, 500); }); test('connect 2 clients', function(done) { var count = 0; c1Io = io.connect(url, ioOptions); c2Io = io.connect(url, ioOptions); c1Io.on('connect', connected); c2Io.on('connect', connected); function connected() { count += 1; if (count === 2) { setTimeout(done, 1000); } } }); test('register 2 peer peers', {timeout: 60 * 1000}, function(done) { c1Io.once('c-registered', function(data) { c1Id = data.peerId; expect(c1Id).to.be.a.string(); }); c2Io.once('c-registered', function(data) { c2Id = data.peerId; expect(c2Id).to.be.a.string(); }); c1Io.on('c-finger-update', function(data) { expect(data.rowIndex).to.be.a.string(); expect(data.fingerId).to.be.a.string(); c1FingerTable[data.rowIndex] = data.fingerId; }); c2Io.on('c-finger-update', function(data) { expect(data.rowIndex).to.be.a.string(); expect(data.fingerId).to.be.a.string(); c2FingerTable[data.rowIndex] = data.fingerId; }); c1Io.emit('s-register', {}); c2Io.emit('s-register', {}); setTimeout(done, 1000); }); test('send offer', function(done) { var offer = { srcId: c1Id, dstId: c2Id, signalData: 'some stuff' }; c1Io.emit('s-send-offer', {offer: offer}); c1Io.once('c-offer-accepted', function(data) { done(); }); c2Io.once('c-accept-offer', function(data) { data.offer.signalDataReturn = 'some more stuff'; c2Io.emit('s-offer-accepted', data); }); }); });
API_urlBase = "http://api.noders.cl/api";
import gulp from 'gulp'; let plugins = require('gulp-load-plugins')({ pattern: ['*{-,.}*', 'cssnano'] }); gulp.task('jade', () => { return gulp.src('_src/**/*.jade').pipe(plugins.changed('.', { extension: '.html' })).pipe(plugins.jadeInheritance({ basedir: '_src/' })).pipe(plugins.filter(function(file) { return !/\/_/.test(file.path) || !/^_/.test(file.relative); })).pipe(plugins.plumber()).pipe(plugins.jade({ pretty: true, client: false })).pipe(gulp.dest('.')); }); gulp.task('css', () => { let autoprefixer = require('autoprefixer'); let processors = [ autoprefixer({browsers: ['last 2 versions']}), plugins.postcssAssets({loadPaths: ['images/', 'fonts/', '_src/sprite-svg/']}), plugins.postcssInlineSvg({path: '_src/sprite-svg/'}), plugins.cssMqpacker, plugins.cssnano ]; return gulp.src('_src/styles/common.styl') .pipe(plugins.sourcemaps.init({includeContent: false})) .pipe(plugins.plumber()) .pipe(plugins.stylus()) .pipe(plugins.postcss(processors)) .pipe(plugins.rename({suffix: '.min'})) .pipe(plugins.sourcemaps.write('.')) .pipe(gulp.dest('./styles')); }); gulp.task('uglify', () => { return gulp.src('_src/**/*.js') .pipe(plugins.plumber()) .pipe(plugins.concat('common.min.js')) .pipe(plugins.uglify()) .pipe(gulp.dest('scripts')); }); gulp.task('modernizr', () => { return gulp.src('scripts/*.js').pipe(plugins.modernizr({ options: ['setClasses', 'addTest', 'html5printshiv', 'testProp', 'fnBind'], tests: ['forms_placeholder', 'flexbox', 'backgroundsize', 'audio', 'video', 'svg', 'touchevents', 'csstransforms', 'webp'] })).pipe(plugins.uglify()).pipe(gulp.dest('scripts')); }); gulp.task('sprite-png', () => { let spritesmith = require('gulp.spritesmith'); let spriteData = gulp.src('_src/sprite-png/*.png').pipe(spritesmith({ padding: 4, algorithm: 'binary-tree', imgName: 'sprite.png', cssName: 'sprite-png.json', cssTemplate: '_src/sprite-png/_spriteTemplate.hbs', })); let imgStream = spriteData.img .pipe(gulp.dest('images')); let cssStream = spriteData.css .pipe(gulp.dest('_src/styles/sprite-png')); return cssStream; }); gulp.task('sprite-svg', () => { gulp.src('_src/sprite-svg/*.svg') .pipe(plugins.plumber()) .pipe(plugins.svgSprite({ mode: { symbol: { dest: './', dimensions: '-icon', sprite: 'images/sprite.svg', example: { dest: '_sprite-svg.html' }, render: { styl: { dest: '_src/styles/sprite-svg/sprite-svg.styl' } } } }, svg: { xmlDeclaration: false, doctypeDeclaration: false } })) .pipe(gulp.dest('./')); }); gulp.task('imagemin', () => { return gulp.src('images/*').pipe(plugins.newer('images')).pipe(plugins.imagemin({ progressive: true, use: [plugins.imageminPngquant()] })).pipe(gulp.dest('images')); }); gulp.task('browser-sync', () => { return plugins.browserSync.init(['*.html', 'styles/common.min.css', '**/*.{png,jpg,svg}', 'scripts/main.js', 'scripts/common.min.js'], { open: false, server: { baseDir: '.' } }); }); gulp.task('default', ['browser-sync'], () => { gulp.watch('_src/**/*.styl', ['css']); gulp.watch('_src/**/*.jade', ['jade']); gulp.watch('_src/**/*.js', ['uglify']); gulp.watch('_src/sprite-png/*.png', ['sprite-png', 'css']); gulp.watch('_src/sprite-svg/*.svg', ['sprite-svg']); gulp.watch('images/**/*.{png,jpg}', ['imagemin']); });
// navbar controller function SearchCtrl($scope, apiService, $stateParams) { $scope.resultsList = []; // log out $scope.getSearchResults = function() { apiService.apiCall(function(data, status) { if (status === 200) { $scope.resultsList = data.results; } else { } }, 'GET', '/api/search', { query: $stateParams.query }); }; $scope.getSearchResults(); } SearchCtrl.$inject = ['$scope', 'apiService', '$stateParams'];
import { BasePlugin } from '../base' import mdcGridList from './mdc-grid-list.vue' import mdcGridTile from './mdc-grid-tile.vue' export { mdcGridList, mdcGridTile } export default BasePlugin({ mdcGridList, mdcGridTile })
//jshint strict: false module.exports = function(config) { config.set({ basePath: 'portal', files: [ 'bower_components/angular/angular.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-mocks/angular-mocks.js', 'components/**/*.js', 'view*/**/*.js' ], autoWatch: true, frameworks: ['jasmine'], browsers: ['Chrome'], plugins: [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter: { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
var elasticsearch = require('../../src/elasticsearch'); var _ = require('lodash-node'); var clock = require('sinon').useFakeTimers(); var es = elasticsearch.Client({ host: 'localhost:5555', log: false }); es.search({ index: '_all', type: '_all', body: { query: { match_all: {} } } }, function (err, resp) { var conn = _.union(es.transport.connectionPool._conns.dead, es.transport.connectionPool._conns.alive).pop(); es.close(); if (_.size(clock.timeouts)) { console.log('Timeouts were left behind'); console.log(clock); } clock.restore(); var destroyedSockets = 0; function countDestroyed(sockets) { destroyedSockets += _.where(sockets, { destroyed: true}).length; } _.each(conn.agent.sockets, countDestroyed); _.each(conn.agent.freeSockets, countDestroyed); console.log(destroyedSockets); }); clock.tick(1);
import 'moment/locale/de-ch'; import * as FullCalendar from 'fullcalendar'; /* German initialisation for the jQuery UI date picker plugin. */ /* Written by Milian Wolff (mail@milianw.de). */ FullCalendar.datepickerLocale('de-ch', 'de', { closeText: "Schließen", prevText: "&#x3C;Zurück", nextText: "Vor&#x3E;", currentText: "Heute", monthNames: [ "Januar","Februar","März","April","Mai","Juni", "Juli","August","September","Oktober","November","Dezember" ], monthNamesShort: [ "Jan","Feb","Mär","Apr","Mai","Jun", "Jul","Aug","Sep","Okt","Nov","Dez" ], dayNames: [ "Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag" ], dayNamesShort: [ "So","Mo","Di","Mi","Do","Fr","Sa" ], dayNamesMin: [ "So","Mo","Di","Mi","Do","Fr","Sa" ], weekHeader: "KW", dateFormat: "dd.mm.yy", firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: "" }); FullCalendar.locale("de-ch", { buttonText: { month: "Monat", week: "Woche", day: "Tag", list: "Terminübersicht" }, allDayText: "Ganztägig", eventLimitText: function(n) { return "+ weitere " + n; }, noEventsMessage: "Keine Ereignisse anzuzeigen" });
export { default } from './src/infinite-calendar.vue';
const CommandMixin = { handle(name, handler) { if (!this._handlers) { this._handlers = {}; } if (this._handlers[name]) { throw new TypeError(`Another handler for command "${name}" is already registered.`); } this._handlers[name] = handler; }, unhandle(name) { if (!this.handlerRegistered(name)) { throw new TypeError(`Handler for command "${name}" is not registered.`); } delete this._handlers[name]; }, request(name, options) { if (!this.handlerRegistered(name)) { throw new TypeError(`Handler for command "${name}" is not registered.`); } return this._handlers[name](options || {}); }, execute(name, options) { this.request(name, options); }, handlerRegistered(name) { return this._handlers && !!this._handlers[name]; } }; export default CommandMixin;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import Sampler from './audio/sampler' import { reducer, log } from "./actions/reducer" import { actions, initialState } from "./actions" import './index.css'; const files = { Q: "A1_1", W: "A1_2", E: "B1_1", A: "B2_1", S: "D1_1", D: "D1_2", Z: "V1_1", X: "V2_1", C: "V2_2" } const sampler = new Sampler(files) const reduce = log(true, reducer(initialState, actions, { sampler })) ReactDOM.render( <App reduce={reduce} />, document.getElementById('root') );
const origraph = require('../dist/origraph.cjs.js'); const utils = require('./utils.js'); describe('Interpretation Tests', () => { afterEach(() => { origraph.deleteAllModels(); }); test('Movie + Person nodes + Connections', async () => { expect.assertions(1); await utils.setupSmallMovies(); expect(origraph.currentModel.getModelDump()) .toEqual(require('./interpretationDumps/movies.json')); }); test('Simple self edge test', async () => { expect.assertions(1); let [ nodeClass ] = await utils.loadFiles(['csvTest.csv']); nodeClass = nodeClass.interpretAsNodes(); nodeClass.setClassName('Node'); const edgeClass = nodeClass.connectToNodeClass({ otherNodeClass: nodeClass, attribute: 'is', otherAttribute: 'a' }); edgeClass.toggleDirection(); edgeClass.setClassName('Edge'); expect(origraph.currentModel.getModelDump()) .toEqual(require('./interpretationDumps/selfEdge.json')); }); test('Movies to Edges', async () => { expect.assertions(1); let { movies } = await utils.setupSmallMovies(); // Reinterpret Movies as Edges movies.interpretAsEdges({ autoconnect: true }); expect(origraph.currentModel.getModelDump()) .toEqual(require('./interpretationDumps/movies_asEdges.json')); }); test('Movies to Edges and Back Again', async () => { expect.assertions(1); let { movies } = await utils.setupSmallMovies(); // Reinterpret Movies as Edges movies = movies.interpretAsEdges({ autoconnect: true }); // Reinterpret Movies as Nodes movies.interpretAsNodes(); expect(origraph.currentModel.getModelDump()) .toEqual(require('./interpretationDumps/movies_asEdgesAndBack.json')); }); test('Northwind test', async () => { expect.assertions(1); await utils.setupNorthwind(); expect(origraph.currentModel.getModelDump()) .toEqual(require('./interpretationDumps/northwind.json')); }); });
var big= require("../bn"); var UInt64; var maxU64Big; var toArrayLike= big.prototype.toArrayLike; var U1; big.prototype.inspect= function(){ return this.toString() } UInt64=module.exports=function(){ big.apply(this,arguments); } UInt64.prototype = Object.create(big.prototype); UInt64.prototype.__constructor= UInt64; UInt64._get= function(number){ var str= number.toString() if(!this._int64){ this._int64=new UInt64(null); } this._int64._init(str,10); return this._int64; } UInt64.prototype.validate=function(){ if(!this.words){ return; } if(this.bitLength()>64){ throw new core.System.OverflowException("La operación produjo una excepción de desbordamiento"); } if(this.negative!==0){ throw new core.System.OverflowException("La operación produjo una excepción de desbordamiento"); } if(this.words.length>=3){ if(this.words[2]>4095){ throw new core.System.OverflowException("La operación produjo una excepción de desbordamiento"); } } } UInt64.prototype.toInt64= function(){ if(this.words.length>=3 && this.words[2]>=2048){ var ln= maxU64Big.clone(); ln.isub(this); ln.iadd(U1); ln.negative=1; return ln; } return new core.System.Int64(); } UInt64.prototype.toArrayLike= function(){ if(arguments[1]==undefined){ arguments[1]='le'; } if(arguments[2]==undefined){ arguments[2]=8; } return toArrayLike.apply(this, arguments); } UInt64.prototype.shiftLeft= this.shln; /*function(bits){ return this.shln(bits); }*/ UInt64.prototype.shiftRight= this.shrn; /*function(bits){ return this.shrn(bits); }*/ U1= new UInt64(1); maxU64Big= UInt64.maxValue= new UInt64("18446744073709551615"); // [ 67108863, 67108863, 4095 ] UInt64.minValue= new UInt64(0);// [ 0, 0, 0 ]
// Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ /********************************************* This relay module demo toggles both relay channels every two seconds, logging the new values to the console upon latching. *********************************************/ var tessel = require('tessel'); var relaylib = require('relay-mono'); var config = require('../config/config').relay; module.exports = { start: function() { var relay = relaylib.use(tessel.port[config.port]); //On Ready: Wait for the module to connect relay.on('ready', function relayReady () { console.log('Ready! Toggling relays...'); setInterval(function toggle() { // Toggle relay channel 1 relay.toggle(1, function toggleOneResult(err) { if (err) console.log("Err toggling 1", err); }); // Toggle relay channel 2 relay.toggle(2, function toggleTwoResult(err) { if (err) console.log("Err toggling 2", err); }); }, 2000); // Every 2 seconds (2000ms) }); // When a relay channel is set, it emits the 'latch' event relay.on('latch', function(channel, value) { console.log('latch on relay channel ' + channel + ' switched to', value); }); } }
/** * Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ var fs = require("fs"); var path = require('path'); var runtime = require("./runtime"); var api = require("./api"); process.env.NODE_RED_HOME = process.env.NODE_RED_HOME || path.resolve(__dirname+"/.."); var nodeApp = null; var adminApp = null; var server = null; var apiEnabled = false; function checkVersion(userSettings) { var semver = require('semver'); if (!semver.satisfies(process.version,">=4.0.0")) { // TODO: in the future, make this a hard error. // var e = new Error("Unsupported version of node.js"); // e.code = "unsupported_version"; // throw e; //userSettings.UNSUPPORTED_VERSION = process.version; } } function checkBuild() { var editorFile = path.resolve(path.join(__dirname,"..","public","red","red.min.js")); try { var stats = fs.statSync(editorFile); } catch(err) { var e = new Error("Node-RED not built"); e.code = "not_built"; throw e; } } module.exports = { init: function(httpServer,userSettings) { if (!userSettings) { userSettings = httpServer; httpServer = null; } if (!userSettings.SKIP_BUILD_CHECK) { checkVersion(userSettings); checkBuild(); } if (!userSettings.coreNodesDir) { userSettings.coreNodesDir = path.resolve(path.join(__dirname,"..","nodes")); } if (userSettings.httpAdminRoot !== false) { runtime.init(userSettings,api); api.init(httpServer,runtime); apiEnabled = true; } else { runtime.init(userSettings); apiEnabled = false; } adminApp = runtime.adminApi.adminApp; nodeApp = runtime.nodeApp; server = runtime.adminApi.server; return; }, start: function() { return runtime.start().then(function() { if (apiEnabled) { return api.start(); } }); }, stop: function() { return runtime.stop().then(function() { if (apiEnabled) { return api.stop(); } }) }, nodes: runtime.nodes, log: runtime.log, settings:runtime.settings, util: runtime.util, version: runtime.version, comms: api.comms, library: api.library, auth: api.auth, get app() { console.log("Deprecated use of RED.app - use RED.httpAdmin instead"); return runtime.app }, get httpAdmin() { return adminApp }, get httpNode() { return nodeApp }, get server() { return server } };
class RenderConditionDiseases { static $getRenderedConditionDisease (it) { const entryList = {type: "entries", entries: it.entries}; const textStack = []; Renderer.get().setFirstSection(true).recursiveRender(entryList, textStack); return $$` ${Renderer.utils.getBorderTr()} ${Renderer.utils.getExcludedTr(it, it.__prop)} ${Renderer.utils.getNameTr(it, {page: UrlUtil.PG_CONDITIONS_DISEASES})} <tr><td class="divider" colspan="6"><div></div></td></tr> <tr class="text"><td colspan="6">${textStack.join("")}</td></tr> ${Renderer.utils.getPageTr(it)} ${Renderer.utils.getBorderTr()} ` } }
const _ = require('underscore'); module.exports = function _createAdapter(adapter, params) { return Promise.resolve() .then(() => { if (_(adapter).isFunction()) { return adapter; } else { const adapterPath = this._resolveModulePath(adapter); return this._loadModule(adapterPath); } }) .then((Adapter) => this._promisifyAdapter(new Adapter(params))) .catch((err) => { throw new Error(`Error during adapter creation: ${err.message}`); }); };
/*jshint esversion: 6 */ /* global __dirname */ (function() { 'use strict'; const _ = require('lodash'); const util = require('util'); const moment = require('moment'); const normalize = require('normalize-space'); const AbstractTwebHtmlScraper = require(__dirname + '/../abstract-tweb-html-scraper'); /** * Vantaa TWeb specific implementation of Html scraper */ class VantaaTwebHtmlScraper extends AbstractTwebHtmlScraper { constructor(options) { super(); this.options = Object.assign({ "host": "paatokset.vantaa.fi", "searchFormPath": "/ktwebbin/dbisa.dll/ktwebscr/epj_tek_tweb.htm", "eventsPath": "/ktwebbin/dbisa.dll/ktwebscr/pk_kokl_tweb.htm", "eventPath": "/ktwebbin/dbisa.dll/ktwebscr/pk_asil_tweb.htm", "eventCaseAttachmentsPath": "/ktwebbin/dbisa.dll/ktwebscr/epjattn_tweb.htm", "encoding": "binary" }, options || {}); } /** * Returns a promise for organization event cases. * * Returned data is ordered in same order that it is in html page. * * @param {String} eventId eventId where to scrape cases */ extractOrganizationEventActions(eventId) { return new Promise((resolve, reject) => { var options = { "url": util.format("http://%s%s", this.options.host, this.options.eventPath), "method": "GET", "encoding": this.options.encoding, "qs": { "+bid": eventId }, "qsStringifyOptions": { encode: false }, "htmlDownloadInterval": this.options.htmlDownloadInterval }; this.getParsedHtml(options) .then(($) => { var actions = []; var rows = $('table.list tr[class*="data"]').filter((index, row) => { return !!$(row).find('td:nth-of-type(1)').text() && !!$(row).find('td:nth-of-type(3) a').attr('href'); }); rows.each((index, row) => { var link = $(row).find('td:nth-of-type(3) a'); var linkHref = link.attr('href'); var idMatch = /(.*docid=)([0-9]*)(.*)/.exec(linkHref); var id = idMatch[2]; var articleNumber = $(row).find('td:nth-of-type(1)').text(); var title = normalize(link.text()); actions.push({ "sourceId": id, "articleNumber": articleNumber, "title": title, "ordering": index, "eventId": eventId }); }); resolve(actions); }) .catch(reject); }); } getEventName(name, startDate, endDate) { var colonIndex = name.indexOf(':'); if (colonIndex > -1 && startDate) { return util.format("%s %s", name.substring(0, colonIndex), startDate.format('D.M.YYYY')); } return name; } } module.exports = VantaaTwebHtmlScraper; }).call(this);
module.exports = function (indexedStore, test) { test("matches IDBFactory interface", function (t) { t.ok(indexedStore.open, "does not have open method") t.ok(indexedStore.deleteDatabase, "does not have deleteDatabase") t.ok(indexedStore.cmp, "does not have cmp method") t.end() }) test("compare keys", function (t) { var cmp = indexedStore.cmp t.equal(cmp("b", "a"), 1, "cmp thinks b is less than a") t.equal(cmp("a", "b"), -1, "cmp thinks a is greater then b") t.equal(cmp("b", "b"), 0, "cmp thinks b is not equal to be") //TODO: more comparison tests t.equal(cmp(["b", 10], ["b", 5]), 1, "cmp thinks 10 is less than 5") t.equal(cmp(["b", 5], ["b", 10]), -1, "cmp thinks 5 is greater than 10") t.equal(cmp(["b", 5], ["b", 5]), 0, "cmp thinks arrays are not equal") t.end() }) test("test can open database", function (t) { t.plan(2) //t.log("opening db") indexedStore.open("testling", function (err, connection) { //t.log("opened" + connection) if (err !== null) { t.log("error open", err) } t.equal(err, null, "we have an error") t.ok(connection, "we dont have a connection") t.end() }) }) test("test can delete database", function (t) { t.plan(2) //t.log("deleting db" + indexedStore.deleteDatabase) indexedStore.deleteDatabase("testling", function (err, result) { t.equal(err, null, "we have an error") t.equal(result, null, "result is not null") t.end() }) }) }
'use strict'; /* global logger */ const _ = require('lodash'); const H = require('higher'); const EngineHelpers = require('@getlazy/engine-helpers'); const HelperContainer = EngineHelpers.HelperContainer; const EngineHttpServer = EngineHelpers.EngineHttpServer; // We are implicitly using `this` in overridden methods but eslint keep telling us not to. // lazy ignore class-methods-use-this class PmdJavaHelperContainer extends HelperContainer { constructor() { // Per image-metadata our helper container ID is pmd-java. super('pmd-java'); } _getBaseContainerExecParams() { return { User: 'root', Cmd: ['/usr/local/pmd-bin/bin/run.sh', 'pmd', '-R', 'java-basic,java-typeresolution', '-f', 'codeclimate', '-d'] }; } _processContainerOutput(buffers) { // In this engine each line is a separate JSON so we first put together all the buffers // and then we split them per lines. const jsonLines = _ .chain(buffers) .map(buffer => buffer && buffer.payload && buffer.payload.toString()) .join('') .split('\n') .value(); // Once the output has been split into lines, parse each line and create a warning for it. return { warnings: _ .chain(jsonLines) .reject(_.isEmpty) .map((jsonLine) => { try { // Clean \u0000 at the end of the jsonLine. let cleanJsonLine; if (_.last(jsonLine) === '\u0000') { cleanJsonLine = jsonLine.slice(0, jsonLine.length - 1); } else { cleanJsonLine = jsonLine; } const warning = JSON.parse(cleanJsonLine); return { type: 'Warning', line: H.ifFalsy(_.get(warning, 'location.lines.begin'), 0), column: 1, message: warning.description }; } catch (e) { logger.error('Failed to parse JSON', jsonLine, e); return null; } }) .filter() .value() }; } } class PmdJavaEngineHttpServer extends EngineHttpServer { beforeListening() { this._helperContainer = new PmdJavaHelperContainer(); return Promise.resolve(); } getMeta() { return { languages: ['Java'] }; } analyzeFile(...args) { // Pass forward the arguments to the engine. return this._helperContainer.analyzeFile(...args) .then((result) => { // Mark the code as checked. _.assignIn(result, { status: { codeChecked: true } }); return result; }); } afterListening() { this._helperContainer = null; return Promise.resolve(); } } class Engine { start() { const port = process.env.PORT || 80; this._server = new PmdJavaEngineHttpServer(port); return this._server.start(); } stop() { return this._server.stop() .then(() => { this._server = null; }); } } module.exports = Engine;
/* * DialPad * * This is the first thing users see of our App, at the '/' route */ /* global Twilio b:true */ import React from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; import { Icon } from 'semantic-ui-react'; import Button from 'components/Button'; import Card from 'components/Card'; import DialPadWrapper from 'components/DialPadWrapper'; import DialPadKey from 'components/DialPadKey'; import DialPadInput from 'components/DialPadInput'; import Loading from 'components/Loading'; import Info from './Info'; import keysConfig from './config'; import { addDigit, removeDigit, } from './actions'; import { selectCurrentNumber, } from './selectors'; import { selectTwilioReady, } from '../App/selectors'; export class DialPad extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function componentDidMount() { document.addEventListener('keydown', this.handleKeyDown); } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyDown); } /** * DialPadKey Click Handler * @param {Event} e - button event */ onDialButtonClick = (event) => { const { value } = event.currentTarget; this.props.onDialButton(value); }; /** * Delete Button click Handler */ onDeleteNumber = () => { this.props.onDeleteButton(); }; /** * Call Button Click Handler */ onCall = () => { const { phoneNumber } = this.props; if (+phoneNumber.length >= 5) { const params = { To: +phoneNumber, }; Twilio.Device.connect(params); } }; /** * onDialKeyPressed Click Handler * @param {Event} e - key pressed event */ handleKeyDown = (event) => { const acceptedKey = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '#']; const { key } = event; if (acceptedKey.indexOf(key) > -1) { this.props.onDialButton(key); } if (key === 'Backspace') { this.props.onDeleteButton(); } }; render() { const { isTwilioReady, phoneNumber } = this.props; return ( <div> { !isTwilioReady && (<Loading />) } { isTwilioReady && ( <Card> <DialPadInput number={phoneNumber} onDelete={this.onDeleteNumber} /> <DialPadWrapper> { keysConfig.map((key) => <DialPadKey key={key.value} onClick={this.onDialButtonClick} value={key.value} alias={key.alias} /> )} </DialPadWrapper> <Button onClick={this.onCall} success block xl > <Icon name="call" inverted /> </Button> <Info> <FormattedMessage {...messages.info} /> </Info> </Card> )} </div> ); } } DialPad.propTypes = { phoneNumber: React.PropTypes.string, onDialButton: React.PropTypes.func, onDeleteButton: React.PropTypes.func, isTwilioReady: React.PropTypes.bool, }; const mapStateToProps = createStructuredSelector({ phoneNumber: selectCurrentNumber(), isTwilioReady: selectTwilioReady(), }); function mapDispatchToProps(dispatch) { return { onDialButton: (n) => dispatch(addDigit(n)), onDeleteButton: () => dispatch(removeDigit()), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(DialPad);
function Game(frame) { this.framesLog = typeof frame !== 'undefined' ? frame : new Frame(); } Game.prototype.bowlA = function(numberOfPins) { var error = 'Nope. Ten pins max per frame' if (this._isEndOfGame()) {return 'Game over: Ten frames played'} if (this._isTooManyPins(numberOfPins)) {throw new Error(error)} this.framesLog.receivePins(numberOfPins); } Game.prototype.seeFrameResults = function() { return this.framesLog.getFrameResults(); } Game.prototype.seeFrameScores = function() { return this.framesLog.getFrameScores(); } Game.prototype.totalScore = function() { return this.framesLog.totalScore() }; Game.prototype._isEndOfGame = function() { if (this._isLastFrameSpare()) { return this._isSpareComplete(); } if (this._isLastFrameStrike()) { return this._isStrikeComplete(); } return this._isNoBonusBallsAndTenCompleteFrames(); }; Game.prototype._isTooManyPins = function(numberOfPins) { return (this.framesLog.isTooManyPinsInOneFrame(numberOfPins)); }; Game.prototype._isLastFrameSpare = function() { return (typeof this.framesLog.frames[9] !== 'undefined') && (this.framesLog.frames[9].reduce((a, b) => a + b, 0) === 10) && (this.framesLog.frames[9].length === 2); }; Game.prototype._isLastFrameStrike = function() { return (typeof this.framesLog.frames[9] !== 'undefined') && (this.framesLog.frames[9].reduce((a, b) => a + b, 0) === 10) && (this.framesLog.frames[9].length === 1); } Game.prototype._isSpareComplete = function() { if (this.framesLog.currentFrame.length === 1) { return true; } else { return false; } }; Game.prototype._isStrikeComplete = function() { if ((typeof this.framesLog.frames[10] !== 'undefined') && (this.framesLog.frames[10].length === 2)) { return true; } if ((typeof this.framesLog.frames[10] !== 'undefined') && (this.framesLog.frames[10].length === 1) && (typeof this.framesLog.frames[11] !== 'undefined')) { return true; } return false; }; Game.prototype._isNoBonusBallsAndTenCompleteFrames = function () { return this.framesLog.frames.length >= 10 };
/** * Created by yossale on 4/1/14. */ module.exports = { RESOURCE_SIZE: 100, RESOURCE_USE_RATE: 10 }
/** * @author musicq * @create 2016-9-26 */ const express = require('express'); const path = require('path'); const favicon = require('serve-favicon'); const bodyParser = require('body-parser'); const helmet = require('helmet'); const compression = require('compression'); const cookieParser = require('cookie-parser'); const app = express(); app.use(compression()); app.use(helmet()); app.use(favicon(path.join(__dirname, 'favicon.ico'))); app.use(bodyParser.json()); app.use(cookieParser()); /** * 接口全部放在 /api 路径下 */ app.use('/api', require('./routes/router')); /** * 配置环境 * * NODE_ENV 变量: * [development | dev] 开发环境 * [staging] 测试环境 * [production | prod] 正式环境 */ console.log('process.env.NODE_ENV:' + process.env.NODE_ENV); if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'dev') { console.log('开发环境'); } else { (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'prod') ? console.log('正式环境') : console.log('测试环境'); app.use(express.static(path.join(__dirname, 'dist'))); // 除开发环境外,其他环境(正式、测试)全都为下面入口 // `**` 使得匹配到的全部路径都发送到 angular2 来启动程序 app.use('**', express.static(path.join(__dirname, '/dist/index.html'))) } /** * 错误处理 */ // 捕捉 404 错误 app.use((req, res, next) => { let err = new Error('Not Found'); err.status = 404; next(err); }); // 处理错误,返回错误信息 app.use((err, req, res, next) => { res.status(err.status || 500); res.json({ message: err.message, error : err }); }); module.exports = app;
'use strict'; const assert = require('assert'); const app = require('../../../src/app'); describe('os_project service', function() { it('registered the os_projects service', () => { assert.ok(app.service('/api/os_projects')); }); });
/** * <%= appName %> * @module <%= _.camelize(appName) %>.config */ angular.module('<%= _.camelize(appName) %>.config', [ 'user', 'template.app', 'ui.router'<% if (ngModules) { %>, <%= ngModules %><% } %> ]) .constant('NAV_ITEMS', [ {title: 'Home', state: 'home', sref: 'home', icon: 'glyphicon-home'}, {title: 'About', state: 'about', sref: 'about', icon: 'glyphicon-info-sign'}, {title: 'Contact', state: 'contact', sref: 'contact', icon: 'glyphicon-earphone'}, {title: 'My account', state: 'user', sref: 'user.dashboard', icon: 'glyphicon-user'} ]) .config(function ($stateProvider, $urlRouterProvider) { 'use strict'; $urlRouterProvider.otherwise('/home'); $stateProvider .state('home', { url: '/home', templateUrl: 'app/view/home.tpl.html', controller: 'HomeCtrl' }) .state('about', { url: '/about', templateUrl: 'app/view/about.tpl.html' }) .state('contact', { url: '/contact', templateUrl: 'app/view/contact.tpl.html' }); });
import React from 'react' import quote from '../images/quotes.png' function Testimonial(props) { return ( <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-start', }} > <img src={quote} alt="Quote Symbol" style={{ marginTop: '0.2rem', }} /> <div style={{ textAlign: 'left', width: 450, marginLeft: '0.5rem', marginBottom: '0.5rem', background: '#ffffff', padding: '0.25rem 0.5rem', borderRadius: '5px', }} > <p style={{ fontSize: '0.8rem', marginBottom: 0, lineHeight: 1.5, }} > {props.text} </p> <span style={{ color: '#A9A9A9', fontStyle: 'italic', fontSize: '0.7rem', display: 'block', }} > — {props.name} </span> </div> </div> ) } export default Testimonial
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; ENV.contentSecurityPolicy = { 'default-src': "'none'", 'script-src': "'self' 'unsafe-inline'", 'font-src': "'self'", 'connect-src': "'self'", 'img-src': "'self'", 'style-src': "'self'", 'media-src': "'self'" } if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
import Express from 'express'; import http from 'http'; import morgan from 'morgan'; import bodyParser from 'body-parser'; import cors from 'cors'; import helmet from 'helmet'; import cookieParser from 'cookie-parser'; import fs from 'fs'; import auth from './middlewares/auth'; // API routes import routes from './routes.js'; const app = new Express(); const server = new http.Server(app); const logPath = __dirname + '/../logs/api.log'; const accessLogStream = fs.createWriteStream(logPath, { flags: 'a' }); app.set('trust proxy', 1); app.use(cookieParser()); app.use(morgan('combined', { stream: accessLogStream })); app.use(bodyParser.urlencoded({ extended: false, })); app.use(bodyParser.json()); app.use(cors()); app.use(helmet()); app.use(auth); app.use(routes); server.listen(3030, () => { const host = server.address().address; const port = server.address().port; console.log('Api is listening on http://%s:%s', host, port); });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.7.3-2 description: > Number constructor - [[Prototype]] is the Function prototype object (using getPrototypeOf) includes: [runTestCase.js] ---*/ function testcase() { var p = Object.getPrototypeOf(Number); if (p === Function.prototype) { return true; } } runTestCase(testcase);
'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise('/'); // Home state routing $stateProvider. state('search', { url: '/search/:page/:keyword/:searchtype', templateUrl: 'modules/core/views/search.client.view.html' }). state('home', { url: '/', templateUrl: 'modules/core/views/home.client.view.html' }); } ]);
/** * Created by huweijian on 16/5/4. * webpack基础配置 按顺序自上而下 * */ var path = require('path'), config = require('../config'), webpack = require('webpack'), //webpack插件 ExtractPlugin = require('extract-text-webpack-plugin'), projectRoot = path.resolve(__dirname, '../src'); module.exports = { //入口配置,可以用数组配置多个 // todo 后面可能会改动 entry: { //app: path.resolve(__dirname, projectRoot+'/src/app.js') app: './src/app.js' }, //出口配置, // todo 后面可能会改动 output: { path: config.build.assetsDev, filename: '[name].js', // chunkFilename:'[name].js', publicPath: 'http://localhost:3000/', assetsPublicPath: config.build.assetsPublicPath }, plugins: [ new ExtractPlugin('[name].css',{allChunks: true}), new webpack.optimize.CommonsChunkPlugin({ //把用到的依赖放入名为main的文件 name: 'main', //寻找所有具有功能依赖关系的子项 children: true, //一个依赖被使用多少次才能被提取 minChunks: 2 }) ], module: { preLoaders: [ // { // test: /\.js/, // loader: 'eslint', // include: './src', // exclude: ['../node_modules', '../bower_components'] // }, // { // test: /\.vue$/, // loader: 'eslint', // include: './src', // exclude: ['../node_modules', '../bower_components'] // } ], loaders: [ { test: /\.vue$/i, loader: 'vue', //include: __dirname + '../src' exclude: ['../node_modules', '../bower_components'] }, { test: /\.js/, loader: 'babel', include: projectRoot, exclude: ['../node_modules', '../bower_components'] }, { test: /\.css/, loader: ExtractPlugin.extract("style-loader", "css-loader") }, { test: /\.scss$/, loader: ExtractPlugin.extract('style', 'css!sass') }, { test: /\.(png|gif|jpe?g|svg)$/i, loader: 'url?limit=10000' }, { test: /\.html/, loader: 'html' } ] }, externals: [ { 'vue.min': 'Vue', 'jquery.min': '$' } ], vue: { autoprefixer: { browsers: ['last 2 versions'] } }, resolve: { alias: { 'vue$': 'vue/dist/vue.js' }, extensions: ['', '.webpack.js', '.web.js', '.js', '.vue'], root: [ projectRoot ] } };
'use strict'; angular.module('fmsApp') .controller('MainCtrl', function ($scope, $http) { $scope.awesomeThings = []; $http.get('/api/things').success(function(awesomeThings) { $scope.awesomeThings = awesomeThings; }); $scope.addThing = function() { if($scope.newThing === '') { return; } $http.post('/api/things', { name: $scope.newThing }); $scope.newThing = ''; }; $scope.deleteThing = function(thing) { $http.delete('/api/things/' + thing._id); }; });
import React from 'react' import ReactDOM from 'react-dom' import Ink from '../src/index' import Test from 'react-dom/test-utils' class Component extends React.Component { render() { return ( <div> <h1>Click anywhere!</h1> <Ink ref="background" radius={150} /> <button style={{ position: 'relative' }} onClick={toggle}> Toggle Stress Test <Ink key="__ink" /> </button> </div> ) } } let playing = false let component = ReactDOM.render(<Component />, document.getElementById('app')) let delta = Date.now() let frame = null function toggle() { if (playing) { cancelAnimationFrame(frame) playing = false } else { playing = true requestAnimationFrame(function click() { if (Date.now() - delta > 1000 / 12) { delta = Date.now() let dom = ReactDOM.findDOMNode(component.refs.background) Test.Simulate.mouseDown(dom, { button: 0, clientX: Math.random() * window.innerWidth, clientY: Math.random() * window.innerHeight }) Test.Simulate.mouseUp(dom) } frame = requestAnimationFrame(click) }) } }
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var React = require('react'); var _ = require('lodash'); var MyComponent = (function (_super) { __extends(MyComponent, _super); function MyComponent() { _super.apply(this, arguments); } MyComponent.prototype.withState = function (act) { this.setState(function (s) { var cloned = _.cloneDeep(s); act(cloned); return cloned; }); }; return MyComponent; }(React.Component)); exports.MyComponent = MyComponent; //# sourceMappingURL=MyComponent.js.map
/* */ "format amd"; var yargs = require('yargs'); var argv = yargs.argv, validBumpTypes = "major|minor|patch|prerelease".split("|"), bump = (argv.bump || 'patch').toLowerCase(); if(validBumpTypes.indexOf(bump) === -1) { throw new Error('Unrecognized bump "' + bump + '".'); } module.exports = { bump: bump };
//= require lib/google_analytics
Reformatter.prototype.base = function() { // this code will be executed first in every reformatter function createStages(rawStages) { /* rawStages = [ 'Stage 1', { 'name': 'Stage 2', 'stages': ['Substage 1','Substage 2'] }, { 'name': 'Stage 3', 'stages': [ 'Substage 1', { 'name': 'Substage 2', 'stages': ['Subsubstage 1', 'Subsubstage 2'] } ] } ] */ return rawStages.map(function(s) { if (typeof(s) === 'string') { return new Stage(s, []); } else { return new Stage(s.name, createStages(s.stages)); } }); } function Stage(name, substages, completionCallback) { this.name = name; this.substages = substages; this.completedSubstages = 0; this.completionCallback = completionCallback; var self = this; this.substages.forEach(function(s) { s.completionCallback = function() { self.completeSubstage(); }; }); } Stage.prototype.getCurrentSubstage = function() { return this.substages[this.completedSubstages]; }; Stage.prototype.completeSubstage = function() { this.completedSubstages++; this.update(); }; Stage.prototype.complete = function() { if (this.completionCallback) { this.completionCallback(); } }; Stage.prototype.setUpdate = function(update) { this.update = update; this.substages.forEach(function(s) { s.setUpdate(update); }); }; function Progress(stages) { this.stages = stages; this.completedStages = 0; this.data = null; var self = this; this.updateCounter = 0; this.update = function() { postMessage(JSON.parse(JSON.stringify(self))); self.updateCounter++; } this.stages.forEach(function(s) { s.setUpdate(self.update); s.completionCallback = function() { self.completedStages++; self.update(); }; }); } Progress.prototype.getCurrentStage = function() { return this.stages[this.completedStages]; }; Progress.prototype.setData = function(data) { this.data = data; this.update(); }; function debug(val) { exit([{ 'name':'debug.json', 'content':JSON.stringify(val,null,2)}], 'debug'); } function error(errorMessage) { exit([{ 'name':'error.txt', 'content': errorMessage}], errorMessage); } function exit(files, throwMessage) { postMessage({ 'data': files, 'stages': [], 'completedStages': 0 }); throw throwMessage; } };
'use strict'; exports.link = require('./lib/link');
'use strict'; angular.module('myApp.isolatedScope', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/directiveWithIsolatedScope', { templateUrl: 'isolatedScope/isolatedScope.html', controller: 'DirectiveIsolatedScopeCtrl' }); }]) .controller('DirectiveIsolatedScopeCtrl',['$scope', function($scope) { //complex object $scope.carFiat={ make:'fiat', hp:500 }; //simple ojbect $scope.colorRed='red'; $scope.colorBlue='blue'; $scope.alert=function(){ alert('Coming from the contoller scope'); } }]) .directive('isolatedDirective',function(){ return { scope: { carFiat:'=fiat', colorRed:'=red', colorBlue:'@blue' }, //use inherit parent scope restrict: "E", templateUrl: '/app/templates/isolatedScope.html', }; }) .filter('upper',function(){ return function (color, areYouSure) { if(areYouSure=='yes'){ var result = color.toUpperCase(); return result; } else{ return color; } } })
// ---------------------------- // import dependencies // ---------------------------- import React, {Component} from 'react'; import axios from 'axios'; import Results from './Results'; import Saved from './Saved'; // import helpers from '../utils/helpers'; // ---------------------------- // render to screen // ---------------------------- class Search extends Component { constructor(props) { super(props); this.state = { topic: '', begin_date: '', end_date: '', results: null, }; this.handleTopic = this.handleTopic.bind(this); this.handleStartDate = this.handleStartDate.bind(this); this.handleEndDate = this.handleEndDate.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleTopic(event) { this.setState({topic: event.target.value}); } handleStartDate(event) { this.setState({begin_date: event.target.value}); } handleEndDate(event) { this.setState({end_date: event.target.value}); } handleSubmit(event) { event.preventDefault(); const nytAPI = 'a306a58c65134177bed7d0955ace8afa'; axios.get('https://api.nytimes.com/svc/search/v2/articlesearch.json', { params: { 'api-key': nytAPI, 'q': this.state.topic, 'begin_date': this.state.begin_date.split("-").join("") || 20100101, 'end_date': this.state.end_date.split("-").join("") || 20170624 } }).then((res) => { // console.log(`ARTICLE:\n ${res.data.response.docs[0].lead_paragraph}`); // console.log('\n') // console.log('\n') // console.log(`LINK:\n ${JSON.stringify(res.data.response.docs[0].web_url)}`); // console.log('\n') // console.log('\n') // console.log(`IMG THUMBNAIL:\n http://${JSON.stringify(res.data.response.docs[0].multimedia)}`); // console.log('\n') // console.log('\n') // console.log(`ALL OF IT!:\n ${JSON.stringify(res)}`); this.setState({ // clear the query after the call topic: "", begin_date: '', end_date: '', results: res }) console.log(this.state); }).catch((error) => { console.log(error); }); } render() { return ( <div className='container'> <div className='row'> <form className='title' onSubmit={this.handleSubmit}> <label> {/* Form */} <p>Article Topic</p> <input className='input--border' type='text' value={this.state.topic} onChange={this.handleTopic} /> <br/> <br/> <p>Start Date</p> <input className='input--border' type='date' id='startdatepicker' data-date-format='yyyy/mm/dd' value={this.state.begin_date} onChange={this.handleStartDate} /> <br/> <br/> <p>End Date</p> <input className='input--border' type='date' id='enddatepicker' data-date-format='yyyy/mm/dd' value={this.state.end_date} onChange={this.handleEndDate} /> </label> <br /> <br /> <input className='btn btn-primary' type='submit' value='Submit' /> </form> <br /> <br /> </div> <div className='row'> {/*this.state.data ? <Results data={this.state.data}*/} {/*this.state.results ? <Results data={this.state.results} /> : <div></div>*/} <Results results={this.state.results} /> <Saved /> </div> </div> ); } } export default Search;
'use strict'; var supertest = require('supertest'); var app = require('../../server'); var expect = require('expect.js'); var faker = require('faker'); faker.locale = 'fr'; var config = require('../../config/config'); var randomUUID = faker.random.uuid(); var randomId = '293660'; var randomSlug = 'deadpool'; var randomImg = faker.image.image(); var randomIndex_1 = faker.lorem.sentence(); var randomIndex_2 = faker.lorem.sentence(); var randomIndex_3 = faker.lorem.sentence(); function request() { return supertest(app.listen()); } // This agent refers to PORT where program is runninng. var server = supertest.agent(config.app.url); // UNIT test begin describe('CRUD Movie',function(){ var id it('post a movie',function(done){ // calling home page api this.timeout(10000); server request() .post('/api/movie') .send({ id_themoviedb: randomId, slug: randomSlug, index_1: randomIndex_1, index_2: randomIndex_2, index_3: randomIndex_3, illu: randomImg }) .set('X-app-UUID', randomUUID) .set('Content-Type', 'application/json') .end(function(err,res){ //console.log(res.body) expect(res.body).to.not.be.empty(); expect(typeof res.body).to.eql('object') expect(res.body.data).to.have.key('slug') expect(res.body.meta.code).to.eql(200) id = res.body.data._id //console.log(id); done(); }); }); it('get a movie - 200',function(done){ this.timeout(5000); server request() .get('/api/movie/' + id) .set('X-app-UUID', randomUUID) .set('Content-Type', 'application/json') .end(function(err,res){ //console.log(res.body) expect(res.body).to.not.be.empty(); expect(typeof res.body).to.eql('object') expect(res.body.data).to.have.key('_id'); expect(res.body.data._id).to.eql(id) expect(res.body.meta.code).to.eql(200) done(); }); }); it('get a movie - 404',function(done){ this.timeout(5000); server request() .get('/api/movie/qsd' + id) .set('X-app-UUID', randomUUID) .set('Content-Type', 'application/json') .end(function(err,res){ //console.log(res.body) //expect(res.body).to.not.be.empty(); expect(res.body.meta.ok).to.eql(false) expect(res.body.meta.code).to.eql(404) done(); }); }); it('get a collection of movies',function(done){ this.timeout(5000); server request() .get('/api/movies') .set('X-app-UUID', randomUUID) .set('Content-Type', 'application/json') .end(function(err,res){ //console.log(res.body) expect(res.body).to.not.be.empty(); expect(typeof res.body).to.eql('object') expect(err).to.eql(null) expect(res.body.data.map(function (item){return item._id})).to.contain(id) expect(res.body.meta.code).to.eql(200) done(); }); }); it('update a movie', function(done){ this.timeout(5000); server request() .put('/api/movie/' + id) .send({ id_themoviedb: randomId, slug: randomSlug + '-updated', index_1: randomIndex_1, index_2: randomIndex_2, index_3: randomIndex_3, illu: randomImg }) .set('X-app-UUID', randomUUID) .set('Content-Type', 'application/json') .end(function(err,res){ //console.log(res.body) expect(err).to.eql(null) expect(typeof res.body).to.eql('object') expect(res.body.meta.ok).to.eql(true) expect(res.body.meta.code).to.eql(200) done(); }); }) it('checks an updated movie', function(done){ this.timeout(5000); server request() .get('/api/movie/' + id) .set('X-app-UUID', randomUUID) .set('Content-Type', 'application/json') .end(function(err, res){ // console.log(res.body) expect(err).to.eql(null) expect(typeof res.body).to.eql('object') expect(res.body.data._id).to.eql(id) expect(res.body.data.slug).to.eql(randomSlug + '-updated') done() }) }) it('removes a movie', function(done){ this.timeout(5000); server request() .del('/api/movie/' + id) .set('X-app-UUID', randomUUID) .set('Content-Type', 'application/json') .end(function(err, res){ // console.log(res.body) expect(err).to.eql(null) expect(typeof res.body).to.eql('object') expect(res.body.meta.ok).to.eql(true) expect(res.body.meta.code).to.eql(200) done() }) }) });
// Import the page-mod API var pageMod = require('sdk/page-mod'); // Import the self API var self = require('sdk/self'); // Import simple-storage API var sstorage = require('sdk/simple-storage'); pageMod.PageMod({ include: ['*.phxbit.com'], contentScriptFile: [ self.data.url('lib/jquery-2.1.4.min.js'), self.data.url('lib/utils.js'), self.data.url('options.js'), self.data.url('main.js'), self.data.url('module/global.module.js'), self.data.url('module/endless_scrolling.module.js'), self.data.url('module/torrent_list.module.js'), self.data.url('module/sphinx.module.js'), self.data.url('module/torrent.module.js'), self.data.url('module/shoutbox.module.js'), self.data.url('module/twits.module.js'), self.data.url('module/forums.module.js'), self.data.url('module/logs.module.js'), self.data.url('module/bookmark.module.js'), self.data.url('module/badge.module.js'), self.data.url('module/my.module.js'), self.data.url('loader.js') ], contentScriptOptions: { 'images/loading.gif': self.data.url('images/loading.gif'), 'images/bookmark.png': self.data.url('images/bookmark.png'), 'images/rss.png': self.data.url('images/rss.png'), 'images/nfo.png': self.data.url('images/nfo.png'), 'images/download.png': self.data.url('images/download.png'), 'images/watch.png': self.data.url('images/watch.png'), 'images/watch_new.png': self.data.url('images/watch_new.png'), 'images/Classic/to_top_small.png': self.data.url('images/Classic/to_top_small.png'), 'images/Classic/endless_scrolling_active.png': self.data.url('images/Classic/endless_scrolling_active.png'), 'images/Classic/endless_scrolling_paused.png': self.data.url('images/Classic/endless_scrolling_paused.png'), 'images/LordVal/to_top_small.png': self.data.url('images/LordVal/to_top_small.png'), 'images/LordVal/endless_scrolling_active.png': self.data.url('images/LordVal/endless_scrolling_active.png'), 'images/LordVal/endless_scrolling_paused.png': self.data.url('images/LordVal/endless_scrolling_paused.png'), 'main.css': self.data.url('main.css') }, contentScriptWhen: 'ready', onAttach: function(worker) { worker.port.on('storageGet', function(key) { worker.port.emit('storageGet' + key, sstorage.storage[key]); }); worker.port.on('storageSet', function(obj) { sstorage.storage[obj.key] = obj.val; }); } });
import {expect, getSdk, getMock, getRegistry} from './test/test'; import SDK from './SDK'; describe('RingCentral', function() { async function test(suite, server, done) { suite.timeout(10000); // Per SLA should be 3 seconds var sdk = new SDK({server: server, appKey: '', appSecret: ''}); try { var response = await sdk.platform().get('', null, {skipAuthCheck: true}); expect(response.json().uri).to.equal(server + '/restapi/v1.0'); sdk.cache().clean(); } catch (e) { throw e; } } it.skip('connects to sandbox', function() { return test(this, SDK.server.sandbox); }); it('connects to production', function() { return test(this, SDK.server.production); }); });
/* eslint no-undef: "off", complexity: 0 */ import delay from 'api/__fakeApi__/delay'; import forumArray from 'api/__fakeData__/forumArray'; import topicArray from 'api/__fakeData__/topicArray'; const getForumBreadcrumbsRecursively = (array, forumId, result = [], index = 1000) => { const selectedForum = array.find(x => x.id === forumId); if (selectedForum && selectedForum.parentForumId) { return getForumBreadcrumbsRecursively(array, selectedForum.parentForumId, [{path: `/Forum/${forumId}`, title: selectedForum.title, order: index}, ...result], index - 1); } else if (selectedForum) { return [{path: `/Forum/${forumId}`, title: selectedForum.title, order: index}, ...result]; } return result; }; const getTopicBreadcrumbsArrayByTopicIdApi = topicId => new Promise(resolve => { const selectedTopic = topicArray.find(x => x.id === topicId); const result = getForumBreadcrumbsRecursively(forumArray, selectedTopic.forumId, [{path: `/Topic/${topicId}`, title: selectedTopic.title, order: 1000}], 999); setTimeout(() => { resolve({response: {data: result}, error: null}); }, delay); }); export default getTopicBreadcrumbsArrayByTopicIdApi;
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { fetchTodos, addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from '../actions'; import AddTodo from '../components/AddTodo'; import TodoList from '../components/TodoList'; import Footer from '../components/Footer'; class App extends Component { componentDidMount() { let { dispatch } = this.props; dispatch(fetchTodos()); } render() { // Injected by connect() call: const { dispatch, visibleTodos, isLoading, visibilityFilter } = this.props; return ( <div> <AddTodo onAddClick={text => dispatch(addTodo(text)) } /> <TodoList todos={visibleTodos} isLoading={isLoading} onTodoClick={index => dispatch(completeTodo(index)) } /> <Footer filter={visibilityFilter} onFilterChange={nextFilter => dispatch(setVisibilityFilter(nextFilter)) } /> </div> ); } } App.propTypes = { visibleTodos: PropTypes.arrayOf(PropTypes.shape({ text: PropTypes.string.isRequired, completed: PropTypes.bool.isRequired })), visibilityFilter: PropTypes.oneOf([ 'SHOW_ALL', 'SHOW_COMPLETED', 'SHOW_ACTIVE' ]).isRequired }; function selectTodos(todos, filter) { switch(filter) { case VisibilityFilters.SHOW_ALL: return todos; case VisibilityFilters.SHOW_COMPLETED: return todos.filter(todo => todo.completed); case VisibilityFilters.SHOW_ACTIVE: return todos.filter(todo => !todo.completed); } } // Which props do we want to inject, given the global state? // Note: use https://github.com/faassen/reselect for better performance. function select(state) { return { visibleTodos: selectTodos(state.todos, state.visibilityFilter), visibilityFilter: state.visibilityFilter, isLoading: state.isLoading }; } // Wrap the component to inject dispatch and state into it export default connect(select)(App);
var mongoose = require('mongoose'); module.exports = mongoose.model('test_http',{ text:String });
/** * readAsByteArray converts a File object to a Uint8Array. * This function is only used on the Apache Cordova platform. * See https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html#read-a-file */ export default function readAsByteArray (chunk) { return new Promise((resolve, reject) => { const reader = new FileReader() reader.onload = () => { const value = new Uint8Array(reader.result) resolve({ value }) } reader.onerror = (err) => { reject(err) } reader.readAsArrayBuffer(chunk) }) }
/*** * meta messages to be displayed. Situations, actor messages, ideas, quick changes in mood etc are cherry picked * and placed into this bucket for simple dissemination to the actors * * Would be nice to add updates on crowd-averaged phenomenon when the change in avg is at a high enough rate. * * Also nice to count how many nodes up */ ActionMessages = new Mongo.Collection('actionMessages'); //schema ActionMessages.schema = new SimpleSchema({ actionId: {type: String, regEx: SimpleSchema.RegEx.Id, optional: false, label: "action Id"} , actorId: {type: String, regEx: SimpleSchema.RegEx.Id, optional: true, label: "actor Id"} // originator, used to blackball trolls , category: {type: String, label:"category"} // crowd emo, crowd int, sit int, etc. Used to style the message. , isAdministrative: {type: Boolean, defaultValue: false, label:"is Administrative"} , icon: {type: String, optional: true, label:"icon"} , msgBody: {type: String, optional: false, label:"message body"} , upVotes: {type: Number, optional: true, defaultValue: 0, label: "up Votes"} , downVotes: {type: Number, optional: true, defaultValue: 0, label: "down Votes"} , createdDT: {type: Date, defaultValue: new Date(), optional: true, label: "Created Date"} }); ActionMessages.attachSchema(ActionMessages.schema); if (Meteor.isServer) { ActionMessages._ensureIndex({ actionId: 1, createdDT: -1 }); } Meteor.methods({ "createActionMessage": (userId, messageDatum) => { //debugger; check(Meteor.userId(), String); check(messageDatum, { actionId: String , actorId: String , category: String , msgBody: String }); let {actorId, actionId} = messageDatum; let actor = ActorUtilities.getConfirmedActor(actorId, actionId, userId); if (actor) { ActionMessageUtilities.createActionMessage(actorId, messageDatum) } }, "voteUpMessage": (userId, messageDatum) => { check(Meteor.userId(), String); check(messageDatum, { messageId: String , actionId: String , actorId: String }); let {actorId, actionId, messageId} = SOSDatum; let actor = ActorUtilities.getConfirmedActor(actorId, actionId, userId); if (actor) { let selector = {_id: messageId} , modifier = { $inc: {upVotes:1} } ; ActionMessages.update(selector, modifier); } }, "voteDownMessage": (userId, messageDatum) => { check(Meteor.userId(), String); check(messageDatum, { messageId: String , actionId: String , actorId: String }); let {actorId, actionId, messageId} = SOSDatum; let actor = ActorUtilities.getConfirmedActor(actorId, actionId, userId); if (actor) { let selector = {_id: messageId} , modifier = { $inc: {downVotes:1} } ; ActionMessages.update(selector, modifier); } }, }); ActionMessageUtilities = {}; /*** * implementation for writing the message doc * ** pretty sure ** that this will run inside a fiber when called from Meteor method on server * todo: confirm that behaviour * @param actorId * @param messageDatum */ ActionMessageUtilities.createActionMessage = (actorId, messageDatum) => { debugger; let { msgBody } = messageDatum; messageDatum.createdDT = new Date(); ActionMessages.insert( messageDatum ); ActorUtilities.updateLastMsg(actorId, msgBody ); }; ActionMessageUtilities.createStandardActionMessage = (featureObj, datumObj, categoryObj) => { let { actorId, actionId, type, description, isAdministrative } = datumObj; let feature = _.findWhere(featureObj, {key: type} ) ,stdMsg = (feature && feature.description) || '' , icon = (feature && feature.icon) || 'info circle' , userMsg = description || '' , msg = `${stdMsg} \n ${userMsg}` ; let msgDatum = ActionMessageUtilities.createMsgDatum(actorId, actionId, msg, categoryObj, icon, !!isAdministrative ) ; ActionMessageUtilities.createActionMessage(actorId, msgDatum); }; ActionMessageUtilities.createMsgDatum = (actorId, actionId, msg, category, icon, isAdministrative) => { let msgDatum = {}; msgDatum.actorId = actorId; msgDatum.actionId = actionId; msgDatum.msgBody = msg; msgDatum.category = category.key; msgDatum.icon = icon msgDatum.isAdministrative = !!isAdministrative return msgDatum; };
Ext.define('Ifresco.store.Tags', { extend: 'Ext.data.Store', fields: ['name','count'], autoLoad: true, proxy: { type: 'ajax', url: Routing.generate('ifresco_client_tag_cloud'), reader: { type: 'json', idProperty: 'name', root: 'tags' } } });
/*! * flatten-arguments <https://github.com/tunnckoCore/flatten-arguments> * * Copyright (c) 2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk) * Released under the MIT license. */ 'use strict' var flatten = require('arr-flatten') var isArguments = require('is-arguments') var manageArguments = require('manage-arguments') module.exports = function flattenArguments (val) { var args = isArguments(val) ? manageArguments(val) : manageArguments(arguments) return flatten(args) }
const { all, resolve } = require('bluebird'); const moment = require('moment'); const { filter, complement, isNil } = require('ramda'); const Question = require('../model/question'); const Student = require('../model/student'); const Answer = require('../model/answer'); function getQuestionsForTeacher(teacherId) { return Question.find({ teacher: teacherId }); } function limitExceeded(question, answer) { if (answer && answer.startDate) { return moment().diff(moment(answer.startDate), 'minutes') >= question.limit; } return false; } function isDone(answer) { return answer && answer.choice != null; } function getQuestionsForStudent(studentId) { return resolve(Student.findById(studentId)) .then(student => Question.find({ classrooms: student.classroom }).lean()) .map(question => { const query = { student: studentId, question: question._id }; return all([question, Answer.findOne(query)]) .spread((question, answer) => { if (limitExceeded(question, answer) || isDone(answer)) { return null; } return { _id: question._id, points: question.points, limit: question.limit, startDate: answer ? answer.startDate : undefined, }; }); }) .then(filter(complement(isNil))); } function getQuestions(user) { return user.model === 'Teacher' ? getQuestionsForTeacher(user._id) : getQuestionsForStudent(user._id); } module.exports = getQuestions;
(function(){ var objects = dragonBones.use("objects"); var geom = dragonBones.use("geom"); function DBObject() { this.global = new objects.DBTransform(); this.origin = new objects.DBTransform(); this.offset = new objects.DBTransform(); this.tween = new objects.DBTransform(); this.tween.scaleX = this.tween.scaleY = 0; this._globalTransformMatrix = new geom.Matrix(); this._visible = true; this._isColorChanged = false; this._isDisplayOnStage = false; this._scaleType = 0; this.fixedRotation = false; } DBObject.prototype.getVisible = function () { return this._visible; }; DBObject.prototype.setVisible = function (value) { this._visible = value; }; DBObject.prototype._setParent = function (value) { this.parent = value; }; DBObject.prototype._setArmature = function (value) { if (this.armature) { this.armature._removeDBObject(this); } this.armature = value; if (this.armature) { this.armature._addDBObject(this); } }; DBObject.prototype.dispose = function () { this.parent = null; this.armature = null; this.global = null; this.origin = null; this.offset = null; this.tween = null; this._globalTransformMatrix = null; }; DBObject.prototype._update = function () { this.global.scaleX = (this.origin.scaleX + this.tween.scaleX) * this.offset.scaleX; this.global.scaleY = (this.origin.scaleY + this.tween.scaleY) * this.offset.scaleY; if (this.parent) { var x = this.origin.x + this.offset.x + this.tween.x; var y = this.origin.y + this.offset.y + this.tween.y; var parentMatrix = this.parent._globalTransformMatrix; this._globalTransformMatrix.tx = this.global.x = parentMatrix.a * x + parentMatrix.c * y + parentMatrix.tx; this._globalTransformMatrix.ty = this.global.y = parentMatrix.d * y + parentMatrix.b * x + parentMatrix.ty; if (this.fixedRotation) { this.global.skewX = this.origin.skewX + this.offset.skewX + this.tween.skewX; this.global.skewY = this.origin.skewY + this.offset.skewY + this.tween.skewY; } else { this.global.skewX = this.origin.skewX + this.offset.skewX + this.tween.skewX + this.parent.global.skewX; this.global.skewY = this.origin.skewY + this.offset.skewY + this.tween.skewY + this.parent.global.skewY; } if (this.parent.scaleMode >= this._scaleType) { this.global.scaleX *= this.parent.global.scaleX; this.global.scaleY *= this.parent.global.scaleY; } } else { this._globalTransformMatrix.tx = this.global.x = this.origin.x + this.offset.x + this.tween.x; this._globalTransformMatrix.ty = this.global.y = this.origin.y + this.offset.y + this.tween.y; this.global.skewX = this.origin.skewX + this.offset.skewX + this.tween.skewX; this.global.skewY = this.origin.skewY + this.offset.skewY + this.tween.skewY; } this._globalTransformMatrix.a = this.global.scaleX * Math.cos(this.global.skewY); this._globalTransformMatrix.b = this.global.scaleX * Math.sin(this.global.skewY); this._globalTransformMatrix.c = -this.global.scaleY * Math.sin(this.global.skewX); this._globalTransformMatrix.d = this.global.scaleY * Math.cos(this.global.skewX); }; dragonBones.DBObject = DBObject; })();
const path = require('path'); const axios = require('axios'); const webpack = require('webpack'); const express = require('express'); const bodyParser = require('body-parser'); const historyApiFallback = require('connect-history-api-fallback'); const WepackDevMiddleware = require('webpack-dev-middleware'); const WebpackHotMiddleware = require('webpack-hot-middleware'); const WebpackDevConfig = require('./webpack/webpack.development.config.js'); const development = process.env.NODE_ENV !== 'production'; if (development) { const dotenv = require('dotenv').config(); } const port = process.env.PORT || 8080; const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.get('/api/darksky', (req, res) => { const ROOT_WEATHER_URL = `https://api.darksky.net/forecast/${process.env.WEATHER_API}`; try { const coords = `${req.query.lat},${req.query.lng}`; const weatherURL = `${ROOT_WEATHER_URL}/${coords}`; axios.get(weatherURL) .then((response) => { if (response.status !== 200) { res.status(response.status).json({"message": "Bad response from Dark Sky server"}); } return response.data; }) .then((payload) => { res.status(200).json(payload); }) .catch((err) => { return err; }) } catch (err) { res.status(500).json({ "message": "Errors occurs requesting Dark Sky API", "details": err }); } }); if (development) { const compiler = webpack(WebpackDevConfig); const middleware = WepackDevMiddleware(compiler, { publicPath: WebpackDevConfig.output.publicPath, contentBase: path.resolve(process.cwd(), 'src/www'), hot: true, stats: { colors: true, hash: false, timings: true, chunks: false, chunkModules: false, modules: false } }); app.use(middleware); app.use(historyApiFallback({ verbose: false })); app.use(middleware); app.use(WebpackHotMiddleware(compiler)); app.get('/', function response(req, res) { res.write(middleware.fileSystem.readFileSync(path.join(__dirname, 'dist/index.html'))); res.end(); }); } else { app.use(express.static(path.resolve(process.cwd(), 'dist'))); app.get('/', function response(req, res) { res.sendFile(path.join(process.cwd(), 'dist/index.html')); }); } app.listen(port, (err) => { if (err) { console.log(err); } else { console.info(`==> 🌎 Server starting on http://localhost:${port} ...`); } });
import * as React from 'react'; import Box from '@mui/material/Box'; import Button from '@mui/material/Button'; import Typography from '@mui/material/Typography'; import Modal from '@mui/material/Modal'; const style = { position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: 400, bgcolor: 'background.paper', border: '2px solid #000', boxShadow: 24, p: 4, }; export default function BasicModal() { const [open, setOpen] = React.useState(false); const handleOpen = () => setOpen(true); const handleClose = () => setOpen(false); return ( <div> <Button onClick={handleOpen}>Open modal</Button> <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <Typography id="modal-modal-title" variant="h6" component="h2"> Text in a modal </Typography> <Typography id="modal-modal-description" sx={{ mt: 2 }}> Duis mollis, est non commodo luctus, nisi erat porttitor ligula. </Typography> </Box> </Modal> </div> ); }
export { default } from 'nypr-account-settings/validations/nypr-accounts/password';
module.exports = function(RED) { function SensorNodeConfig(n) { RED.nodes.createNode(this,n); this.id = n.id; } RED.nodes.registerType("sensor-node-config",SensorNodeConfig); }
require('../setup'); describe('Curriculum', () => { beforeEach(async () => { await uwsws.initialize(config); }); describe('Search by dept', () => { it('should return some that match the query', () => { const options = { dept: 'cse', quarter: 'winter', year: 2015, }; return uwsws.curriculum.search(options) .then((result) => { expect(result.data.Curricula).to.have.length.above(2); }); }); }); describe('search by college', () => { it('should return some that match the query', () => { const options = { college: 'b a', quarter: 'winter', year: 2015, }; return uwsws.curriculum.search(options) .then((result) => { expect(result.data.Curricula).to.have.length.above(4); }); }); }); });
'use strict'; angular.module('photos').controller('PhotosController', ['$scope', '$stateParams', '$http', '$location', 'Authentication', 'Photos', function($scope, $stateParams, $http, $location, Authentication, Photos) { $scope.authentication = Authentication; $scope.likes = 0; $scope.isLiked = false; // Create new Photo $scope.create = function() { // Create new Photo object var photo = new Photos ({ name: this.name }); photo.$save(function(response) { $location.path('photos/' + response._id); // Clear form fields $scope.name = ''; $scope.image = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Photo $scope.remove = function(photo) { if ( photo ) { photo.$remove(); for (var i in $scope.photos) { if ($scope.photos [i] === photo) { $scope.photos.splice(i, 1); } } } else { $scope.photo.$remove(function() { $location.path('photos'); }); } }; // Update existing Photo $scope.update = function() { var photo = $scope.photo; photo.$update(function() { $location.path('photos/' + photo._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Photos $scope.find = function() { $scope.photos = Photos.query(); }; // Find existing Photo $scope.findOne = function() { console.log('Finding one:' + $stateParams.photoId); $scope.photo = Photos.get({ photoId: $stateParams.photoId },function(){ console.log('Photo found'); var user = $scope.authentication.user; var containsValue=false; console.log('ID '+$scope.authentication.user._id); $scope.likes = $scope.photo.likes.length; for(var i=0; i<$scope.photo.likes.length; i++) { console.log('Comparing ' + $scope.photo.likes[i] + ' to ' + user._id + ' is ' + ($scope.photo.likes[i]===user._id).toString()); if($scope.photo.likes[i]===user._id) { containsValue = true; } } $scope.isLiked = containsValue; }); }; //Like a photo $scope.likeThis = function() { var photo = $scope.photo; $http.put('photos/like/' + photo._id).success(function() { // Update the photo with our user ID. photo.likes.push($scope.authentication.user._id); $scope.isLiked=true; }); }; }]);
import delay from './delay'; import exponentialStrategy from './strategy/exponential'; function retryWithBackoff(callback, retryCountBeforeFailure, initialWaitInMilliseconds, backoffStrategy) { retryCountBeforeFailure = retryCountBeforeFailure || 5; initialWaitInMilliseconds = initialWaitInMilliseconds || 250; backoffStrategy = backoffStrategy || exponentialStrategy; var _retryWithCallback = function(callback, retryCount) { return callback().catch(function(reason) { if (retryCount < retryCountBeforeFailure) { return delay(backoffStrategy(initialWaitInMilliseconds, retryCount)).then(function() { return _retryWithCallback(callback, ++retryCount); }); } throw reason; }); } return _retryWithCallback(callback, 0); } export default retryWithBackoff;
import api from './api'; import Interceptors from './Interceptors'; export default (Vue, { store, router }) => { const interceptors = new Interceptors(api, store, router); Object.defineProperty(Vue.prototype, '$api', { get() { return api; } }); };
import Convolve from 'canvas/filters/Convolve.js'; export default function Laplace (imageData) { return Convolve(imageData, [ -1, -1, -1, -1, 8, -1, -1, -1, -1 ]); }
import bcrypt from 'bcrypt' /** * encrypt password provider with bcrypt **/ function encryptPassword (password, cb) { bcrypt.genSalt(10, (err, salt) => { if (err) return cb(err) bcrypt.hash(password, salt, (err, hash) => { if (err) return cb(err) return cb(null, hash) }) }) } /** * compare user password provider with hash **/ function comparePassword (password, currentPassword, cb) { return bcrypt.compare(password, currentPassword, (err, res) => { if (err) return cb(err) return cb(null, res) }) } export { encryptPassword, comparePassword }
//curl -D- -u benjamin.crouzier:morebabyplease -X GET -H "Content-Type: application/json" "" function extractJt(str) { var r1 = R.trim(str).match(/^remotes\/origin\/(jt-[0-9]+)/); var r2 = R.trim(str).match(/^(jt-[0-9]+)/); return (r1 && R.toUpper(r1[1])) || (r2 && R.toUpper(r2[1])); } Meteor.methods({ syncCards: function () { //result.data.issues.length //var url = 'https://jobteaser.atlassian.net/rest/api/2/search?jql=sprint IN openSprints()&project=JT&&maxResults=10000&fields='; //url += 'summary,description,status,assignee'; var url = 'https://jobteaser.atlassian.net/rest/api/2/search?jql=filter=11701&&maxResults=10000&fields='; url += 'summary,description,status,assignee'; var issues = Meteor.http.get(url, { headers: { 'Content-Type': 'application/json', }, 'auth': 'benjamin.crouzier:morebabyplease' }); var board = Boards.findOne({title: 'JT'}); issues.data.issues.forEach(function (issue) { var title = issue.fields.summary; var list = Lists.findOne({title: issue.fields.status.name}); console.log('finding list with name:', issue.fields.status.name); if (!list) return; Cards.remove({title: title}); var card_id = Cards.insert({ title: title, description: issue.fields.description, boardId: board._id, listId: list._id, jiraId: issue.key, jiraBoardType: 'maintenance', }, { validate: false, }); }); }, syncLists: function () { // board var board = Boards.findOne({title: 'JT'}); if (!board) { var board_id = Boards.insert({title: 'JT'}, {validate: false}); board = Boards.findOne(board_id); } //lists var lists = ['Open', 'In Development', 'In Review', 'In Functional Review', 'Ready for Release', 'Released', 'Closed' ]; lists.forEach(function (title) { var existing = Lists.findOne({title: title, boardId: board._id}); if (!existing) { Lists.insert({title: title, boardId: board._id}, {validate: false}); } }); }, syncGit: function() { var exec = Meteor.require('child_process').exec; var cmd = Meteor.wrapAsync(exec); var cwd = '/Users/pinouchon/code/jobteaser/jobteaser'; cmd('git fetch', {cwd: cwd}); cmd('git checkout staging', {cwd: cwd}); cmd('git pull --all', {cwd: cwd}); cmd('git checkout develop', {cwd: cwd}); cmd('git pull --all', {cwd: cwd}); var branchesDevelop = cmd('git branch -a --merged develop', {cwd: cwd}); var branchesStaging = cmd('git branch -a --merged staging', {cwd: cwd}); //var branchesMaster = cmd('git branch -a --merged master', {cwd: cwd}); function jiraIdsFromBranches(branches) { return R.uniq(branches.split('\n').map(extractJt)).filter(R.identity); } var inDevelop = jiraIdsFromBranches(branchesDevelop); var inStaging = jiraIdsFromBranches(branchesStaging); //var inMaster = jiraIdsFromBranches(branchesMaster); Cards.update({}, {$set: {inStaging: false}}, {validate: false, multi: true}); Cards.update({jiraId: {$in: inStaging}}, {$set: {inStaging: true}}, {multi: true}); Cards.update({}, {$set: {inDevelop: false}}, {validate: false, multi: true}); Cards.update({jiraId: {$in: inDevelop}}, {$set: {inDevelop: true}}, {multi: true}); //Cards.update({}, {$set: {inMaster: false}}, {validate: false, multi: true}); //Cards.update({jiraId: {$in: inMaster}}, {$set: {inSMaster: true}}, {multi: true}); }, syncCI: function() { var token = 'circle-token=53f453ef44de0a2bf0db654417c7281cc4ffd160'; var url = 'https://circleci.com/api/v1/recent-builds?' + token + '&limit=30'; var ciResponse = Meteor.http.get(url, {headers: {'Accept': 'application/json'}}); if (ciResponse.statusCode == 200) { var done = []; var json = JSON.parse(ciResponse.content); json.forEach(function(build) { var jiraId = extractJt(build.branch); if (jiraId && !R.contains(jiraId, done)) { Cards.update({jiraId: jiraId}, {$set: {buildStatus: build.status}}, {validate: false}); done.push(jiraId); } }); } else { console.log('Error with CI api'); return 'Error with CI api' } } }); function sync() { //var url = "#{API_URL_PREFIX}#{url_suffix}"; //var API_URL_PREFIX = 'https://jobteaser.atlassian.net/rest/api/2/issue/'; //var API_PORT = 443 // //var headers = { // 'Content-Type': 'application/json' //}; // //var params = DEFAULT_PARAMS.merge({}); // //var credentials = { // username: username, // password: password //}; //R.uniq( // R.map(R.pipe(R.prop('fields'), R.prop('status')), // issues.data.issues). // map(n=>n.name)); // //R.uniq( // issues.data.issues. // map(R.pipe(R.prop('fields'), R.prop('status'))). // map(R.prop('name'))); }
'use strict'; var util = require('util'); module.exports = util; /** * Function for creating a clone of an object * * @param o {Object} object to clone * @return {Object} */ function clone(obj) { if (typeof obj !== 'object') { return obj; } var ret; if (util.isArray(obj)) { ret = []; obj.forEach(function (val) { ret.push(clone(val)); }); return ret; } ret = {}; Object.keys(obj).forEach(function (key) { ret[key] = clone(obj[key]); }); return ret; } /** * A extends B * * util.inherits works only with objects derived from Object * * @return {Object} Extended object */ function extend(a, b, noClone) { // A extends B a = a || {}; if (typeof a !== 'object') { return noClone ? b : clone(b); } if (typeof b !== 'object') { return b; } if (!noClone) { a = clone(a); } Object.keys(b).forEach(function (key) { if (!a.hasOwnProperty(key) || (!(typeof b[key] === 'object' && b[key].length === undefined && b[key].constructor.name === 'Folder') && (typeof b[key] !== 'function'))) { // Simple types a[key] = b[key]; } else { // Complex types a[key] = extend(a[key], b[key], noClone); } }); return a; } module.exports.clone = clone; module.exports.extend = extend;
import ButtonComponent from './-button'; import layout from '../../../templates/components/bootstrap/buttons/expand-button'; import { BuilderForPropTypes, BuilderForPropDefaults } from 'ember-bootstrap-controls/utils/prop-definition-tools'; import { propDefinitions } from './-button'; const { buttonText } = propDefinitions; const newButtonTextDefinitions = { ...buttonText, default: 'Expand' }; const newPropDefinitions = Object.assign({}, propDefinitions, { buttonText: newButtonTextDefinitions }); export default ButtonComponent.extend({ layout, propTypes: BuilderForPropTypes(newPropDefinitions), classNames: ['btn-primary'], getDefaultProps() { return BuilderForPropDefaults(newPropDefinitions) }, });
var amqp = require("amqplib/callback_api"); var args = process.argv.slice(2); if (args.length == 0) { console.log("Usage: receive_logs_direct.js [info] [warning] [error] [hello]"); process.exit(1); } amqp.connect("amqp://localhost", function(err, conn) { conn.createChannel(function(err, ch) { // var ex = 'direct_logs'; var ex = 'amq:topic'; //assertExchange // var type = "direct"; var type = "topic"; ch.assertExchange(ex, type, {durable: false}); // ch.bindQueue('hello', ex, '1234'); // ch.consume('hello', function(msg) { // console.log(" [x] %s: '%s'", msg.fields.routingKey, msg.content.toString()); // }, {noAck: true}); //assertQueue ch.assertQueue('hello', {exclusive: true}, function(err, q) { console.log(' [*] Waiting for logs. To exit press CTRL+C'); args.forEach(function(severity){ ch.bindQueue(q.queue, ex, severity); }); ch.consume(q.queue, function(msg) { console.log(" [x] %s: '%s'", msg.fields.routingKey, msg.content.toString()); }, {noAck: true}); }); // --> bindQueue // --> consume }); });
const AWS = require('aws-sdk'); const tableName = process.env.TABLE_NAME || ''; const topic = process.env.TOPIC || ''; let dynamo; let sns; function publish(rule) { const message = { Message: JSON.stringify({ default: JSON.stringify(rule), }), MessageStructure: 'json', TopicArn: topic, }; return sns.publish(message).promise(); } function work(exclusiveStartKey) { const params = { TableName: tableName, }; if (exclusiveStartKey !== undefined) { params.ExclusiveStartKey = exclusiveStartKey; } return dynamo.scan(params).promise() .then((response) => { if (response.Items.length > 0) { return Promise.all(response.Items.map(publish)) .then(() => { if (response.LastEvaluatedKey !== undefined) { return work(response.LastEvaluatedKey); } return Promise.resolve(); }); } return Promise.resolve(); }); } exports.handler = (event, context, callback) => { dynamo = new AWS.DynamoDB.DocumentClient(); sns = new AWS.SNS(); Promise.resolve() .then(work) .then(response => callback(null, response)) .catch(callback); };
angular.module('DepartmentModule', ['ui.router', 'ngResource', 'ngAnimate']) .config(function ($stateProvider) { $stateProvider .state('home.admin.departments', { url: '/departments', views: { '@': { templateUrl: '/js/private/admin/departments/tpl/list.tpl.html', controller: 'ListDepartmentController' } } //views: { // '@': { // template: function($stateParams) { // return '<div>Category:' + $stateParams.catId + '<ui-view/></div>'; // }, // controller: function() {} // // } //} }) .state('home.admin.departments.edit', { url: '/edit/:depId', views: { '@': { templateUrl: '/js/private/admin/departments/tpl/edit.tpl.html', controller: 'EditDepartmentController' } } }) .state('home.admin.departments.create', { url: '/create/:departmentId', views: { '@': { templateUrl: '/js/private/admin/departments/tpl/edit.tpl.html', controller: 'EditDepartmentController' } } }) //.state('home.admin.depart', { // url: '/depart/:depId', // views: { // '@': { // templateUrl: '/js/private/admin/departments/tpl/list.tpl.html', // controller: 'EditDepartmentController' // } // } //}) .state('home.admin.department', { url: '/department/:depId', views: { '@': { templateUrl: '/js/private/admin/departments/tpl/show.tpl.html', controller: 'DepartmentController' } } }) ; }) .constant('CONF_MODULE_DEPARTMENT', {baseUrl: '/departments/:depId'}) .factory('Departments', function ($resource, CONF_MODULE_DEPARTMENT) { var Departments = $resource( CONF_MODULE_DEPARTMENT.baseUrl, {depId: '@id'}, // Определяем собственный метод update на обоих уровнях, класса и экземпляра { update: { method: 'PUT' } } ); Departments.prototype.getFullName = function () { return this.name; }; Departments.prototype.sc = function () { return this.section; }; Departments.prototype.scs = function () { return this.sections; }; Departments.prototype.ok = function () { return alert(this.section + ': ' + this.name + ' изменён!'); }; Departments.prototype.er = function () { return alert('ОШИБКА!!! ' + this.name + ' - изменения не приняты!'); }; Departments.prototype.getListUrl = function () { return '/admin/departments'; }; Departments.prototype.getEditUrl = function (id) { return '/admin/departments/edit/'+id; }; Departments.prototype.getShowUrl = function (id) { return '/admin/department/'+id; }; Departments.prototype.deactivation = function () { return ' - деактивирован'; }; return Departments; }) ;
import {Animal} from './code-listing-127'; export class AnimalClient { constructor() { this.animal = new Animal("Dog"); console.log(this.animal.greeting("barks")); } } let ac = new AnimalClient(); Animal.echo("roof, roof");
class shockwaveflash_shockwaveflash_12 { constructor() { // int AlignMode () {get} {set} this.AlignMode = undefined; // string AllowFullScreen () {get} {set} this.AllowFullScreen = undefined; // string AllowFullScreenInteractive () {get} {set} this.AllowFullScreenInteractive = undefined; // string AllowNetworking () {get} {set} this.AllowNetworking = undefined; // string AllowScriptAccess () {get} {set} this.AllowScriptAccess = undefined; // int BackgroundColor () {get} {set} this.BackgroundColor = undefined; // string Base () {get} {set} this.Base = undefined; // string BGColor () {get} {set} this.BGColor = undefined; // string BrowserZoom () {get} {set} this.BrowserZoom = undefined; // bool DeviceFont () {get} {set} this.DeviceFont = undefined; // bool EmbedMovie () {get} {set} this.EmbedMovie = undefined; // string FlashVars () {get} {set} this.FlashVars = undefined; // int FrameNum () {get} {set} this.FrameNum = undefined; // IUnknown InlineData () {get} {set} this.InlineData = undefined; // bool IsDependent () {get} {set} this.IsDependent = undefined; // bool Loop () {get} {set} this.Loop = undefined; // bool Menu () {get} {set} this.Menu = undefined; // string Movie () {get} {set} this.Movie = undefined; // string MovieData () {get} {set} this.MovieData = undefined; // bool Playing () {get} {set} this.Playing = undefined; // bool Profile () {get} {set} this.Profile = undefined; // string ProfileAddress () {get} {set} this.ProfileAddress = undefined; // int ProfilePort () {get} {set} this.ProfilePort = undefined; // int Quality () {get} {set} this.Quality = undefined; // string Quality2 () {get} {set} this.Quality2 = undefined; // int ReadyState () {get} this.ReadyState = undefined; // string SAlign () {get} {set} this.SAlign = undefined; // string Scale () {get} {set} this.Scale = undefined; // int ScaleMode () {get} {set} this.ScaleMode = undefined; // bool SeamlessTabbing () {get} {set} this.SeamlessTabbing = undefined; // string SWRemote () {get} {set} this.SWRemote = undefined; // int TotalFrames () {get} this.TotalFrames = undefined; // string WMode () {get} {set} this.WMode = undefined; } // void Back () Back() { } // string CallFunction (string) CallFunction(string) { } // int CurrentFrame () CurrentFrame() { } // void DisableLocalSecurity () DisableLocalSecurity() { } // void EnforceLocalSecurity () EnforceLocalSecurity() { } // int FlashVersion () FlashVersion() { } // void Forward () Forward() { } // bool FrameLoaded (int) FrameLoaded(int) { } // string GetVariable (string) GetVariable(string) { } // void GotoFrame (int) GotoFrame(int) { } // bool IsPlaying () IsPlaying() { } // void LoadMovie (int, string) LoadMovie(int, string) { } // void Pan (int, int, int) Pan(int, int, int) { } // int PercentLoaded () PercentLoaded() { } // void Play () Play() { } // void Rewind () Rewind() { } // void SetReturnValue (string) SetReturnValue(string) { } // void SetVariable (string, string) SetVariable(string, string) { } // void SetZoomRect (int, int, int, int) SetZoomRect(int, int, int, int) { } // void Stop () Stop() { } // void StopPlay () StopPlay() { } // void TCallFrame (string, int) TCallFrame(string, int) { } // void TCallLabel (string, string) TCallLabel(string, string) { } // int TCurrentFrame (string) TCurrentFrame(string) { } // string TCurrentLabel (string) TCurrentLabel(string) { } // string TGetProperty (string, int) TGetProperty(string, int) { } // double TGetPropertyAsNumber (string, int) TGetPropertyAsNumber(string, int) { } // double TGetPropertyNum (string, int) TGetPropertyNum(string, int) { } // void TGotoFrame (string, int) TGotoFrame(string, int) { } // void TGotoLabel (string, string) TGotoLabel(string, string) { } // void TPlay (string) TPlay(string) { } // void TSetProperty (string, int, string) TSetProperty(string, int, string) { } // void TSetPropertyNum (string, int, double) TSetPropertyNum(string, int, double) { } // void TStopPlay (string) TStopPlay(string) { } // void Zoom (int) Zoom(int) { } } module.exports = shockwaveflash_shockwaveflash_12;
/** * Created by v on 2015/6/22. */ ejoy2d.scissor = (function(){ var SCISSOR_MAX = 8; var scissor_tmp_array = new Array(4); var S = {}; S.depth = 0; var box = new Array(SCISSOR_MAX); var i =0; for(i =0; i < SCISSOR_MAX; ++i) { var b = { x:0, y:0, width:0, height:0, }; box[i] = b; } S.box = box; S._intersection = function(b, output) { var newx = b.x > output[0] ? b.x : output[0]; var newy = b.y > output[1] ? b.y : output[1]; var bx = b.x + b.width; var by = b.y + b.height; var ax = output[0] + output[2]; var ay = output[1] + output[3]; var neww = (bx > ax ? ax : bx) - newx; var newh = (by > ay ? ay : by) - newy; output[0] = newx; output[1] = newy; output[2] = neww; output[3] = newh; }; S.push = function(x, y, w, h) { console.assert(this.depth < SCISSOR_MAX); shader.flush(); if (this.depth == 0) { shader.scissortest(1); } if (this.depth >= 1) { scissor_tmp_array[0] = x; scissor_tmp_array[1] = y; scissor_tmp_array[2] = w; scissor_tmp_array[3] = h; this._intersection(this.box[this.depth-1], scissor_tmp_array); x = scissor_tmp_array[0]; y = scissor_tmp_array[1]; w = scissor_tmp_array[2]; h = scissor_tmp_array[3]; } var s = this.box[this.depth++]; s.x = x; s.y = y; s.width = w; s.height = h; ejoy2d.screen.scissor(s.x, s.y, s.width, s.height); }; S.pop = function() { var S = this.S; console.assert(this.depth > 0); shader.flush(); --this.depth; if (this.depth == 0) { shader.scissortest(0); return; } var s = this.box[this.depth-1]; ejoy2d.screen.scissor(s.x, s.y, s.width, s.height); } return S; }());
/** * Created by Session on 17/6/1. */ import React, {Component} from 'react'; import s from './style/index'; export default class Loading extends Component { static defaultProps = { prefixLoad: s.loadingPrefix, loading: true, size: 'default' }; render() { const {prefixLoad, text, size, loading} = this.props; let classTmp = prefixLoad + '-container-graph'; let classNameValue; switch (size) { case 'small': classNameValue = [classTmp, 'loading-small'].join(' '); break; case 'large': classNameValue = [classTmp, 'loading-large'].join(' '); break; default: classNameValue = classTmp; break; } return ( <div> { loading ? ( <div className={prefixLoad}> <div className={`${prefixLoad}-container`}> <div className={classNameValue}> <div /> <div /> <div /> <div /> <div /> <div /> <div /> <div /> </div> <div className={`${prefixLoad}-container-text`}> {text} </div> </div> </div> ) : '' } <div className={`${prefixLoad}-content`}> { React.Children.map(this.props.children, child => (<div>{child} </div>)) } </div> </div> ); } }
/** * Created by dcreey on 8/23/2016. */ var expect = require('expect'); var appName = 'cwv'; describe('aboutCtrl', function() { beforeEach(window.angular.mock.module(appName)); var scope, ctrl; beforeEach(inject(function($controller, $rootScope, $http) { scope = $rootScope.$new(); ctrl = $controller('aboutCtrl', { $scope: scope, $http: $http }); })); it('should expose some global scope', function() { expect(scope).toBeTruthy(); }); it('should expose profileLink', function() { expect(ctrl.emailAddress).toBeTruthy(); }); });
var view = { displayMessage: function(msg) { var messageArea = document.getElementById("messageArea"); messageArea.innerHTML = msg; }, displayHit: function(location) { var cell = document.getElementById(location); cell.setAttribute("class", "hit"); }, displayMiss: function(location) { var cell = document.getElementById(location); cell.setAttribute("class", "miss"); } } var model = { boardSize: 7, numShips: 3, shipLength: 3, shipsSunk: 0, ships: [{ locations: [0, 0, 0], hits: ["", "", ""] }, { locations: [0, 0, 0], hits: ["", "", ""] }, { locations: [0, 0, 0], hits: ["", "", ""] }], fire: function(guess) { for (var i = 0; i < this.numShips; i++) { var ship = this.ships[i]; var locations = ship.locations; var index = locations.indexOf(guess); if (index >= 0) { ship.hits[index] = "hit"; view.displayHit(guess); view.displayMessage("HIT!"); if (this.isSunk(ship)) { view.displayMessage("You sank my battleship!"); this.shipsSunk++; } return true; } } view.displayMiss(guess); view.displayMessage("You missed."); return false; }, isSunk: function(ship) { for (var i = 0; i < this.shipLength; i++) { if (ship.hits[i] !== "hit") { return false; } } return true; }, generateShipLocations: function() { var locations; for (var i = 0; i < this.numShips; i++) { do { locations = this.generateShip(); } while (this.collision(locations)); this.ships[i].locations = locations; } }, generateShip: function() { var direction = Math.floor(Math.random() * 2); var row, col; if (direction === 1) { row = Math.floor(Math.random() * this.boardSize); col = Math.floor(Math.random() * (this.boardSize - this.shipLength)); } else { row = Math.floor(Math.random() * (this.boardSize - this.shipLength)); col = Math.floor(Math.random() * this.boardSize); } var newShipLocations = []; for (var i = 0; i < this.shipLength; i++) { if (direction === 1) { newShipLocations.push(row + "" + (col + i)); } else { newShipLocations.push((row + i) + "" + col); } } return newShipLocations; }, collision: function(locations) { for (var i = 0; i < this.numShips; i++) { var ship = model.ships[i]; for (var j = 0; j < locations.length; j++) { if (ship.locations.indexOf(locations[j]) >= 0) { return true; } } } return false; } } function parseGuess(guess) { var alphabet = ["A", "B", "C", "D", "E", "F", "G"]; if (guess === null || guess.length !== 2) { alert("Oops, please enter a letter and a number on the board."); } else { firstChar = guess.charAt(0); var row = alphabet.indexOf(firstChar); var column = guess.charAt(1); if (isNaN(row) || isNaN(column)) { alert("Oops, that isn't on the board."); } else if (row < 0 || row >= model.boardSize || column < 0 || column >= model.boardSize) { alert("Oops, that's off the board!"); } else { return row + column; } } return null; } var controller = { guesses: 0, processGuess: function(guess) { var location = parseGuess(guess); if (location) { this.guesses++; var hit = model.fire(location); if (hit && model.shipsSunk === model.numShips) { view.displayMessage("You sank all my battleships, in " + this.guesses + " guesses"); } } } } function handleFireButton() { var guessInput = document.getElementById("guessInput"); var guess = guessInput.value.toUpperCase(); controller.processGuess(guess); guessInput.value = ""; } function handleKeyPress(e) { var fireButton = document.getElementById("fireButton"); if (e.keyCode === 13) { fireButton.click(); return false; } } window.onload = init; function init() { var fireButton = document.getElementById("fireButton"); fireButton.onclick = handleFireButton; var guessInput = document.getElementById("guessInput"); guessInput.onkeypress = handleKeyPress; model.generateShipLocations(); } // controller.processGuess("A0"); // controller.processGuess("A6"); // controller.processGuess("B6"); // controller.processGuess("C6"); // controller.processGuess("C4"); // controller.processGuess("D4"); // controller.processGuess("E4"); // controller.processGuess("B0"); // controller.processGuess("B1"); // controller.processGuess("B2"); // console.log(parseGuess("A0")); // console.log(parseGuess("B6")); // console.log(parseGuess("G3")); // console.log(parseGuess("H0")); // console.log(parseGuess("A7")); // model.fire("53"); // model.fire("06"); // model.fire("16"); // model.fire("26"); // model.fire("34"); // model.fire("24"); // model.fire("44"); // model.fire("12"); // model.fire("11"); // model.fire("10"); // view.displayMiss("00"); // view.displayHit("34"); // view.displayMiss("55"); // view.displayHit("12"); // view.displayMiss("25"); // view.displayHit("26"); // view.displayMessage("Tap tap, is this thing on?");
(function(Object) { Object.Model.Import = Object.Model.PresentationObject.extend({ "initialize" : function() { Object.Model.PresentationObject.prototype.initialize.call(this); } },{ "type" : "Import", "attributes" : _.defaults({ "texture" : { "type" : "res-texture", "name" : "texture", "_default" : "" }, "geometry" : { "type" : "res-geometry", "name" : "geometry", "_default" : "" }, "nolighting" : { "type" : "bool", "name" : "no lighting", "_default" : false }, "name" : { "type" : "string", "_default" : "new Import", "name" : "name" } }, Object.Model.PresentationObject.attributes) }); }(sp.module("object")));
function cdb_loadMasterData(a) { churchInterface.setStatus("Lade Kennzeichen..."); timers.startMasterdata = new Date; jQuery.getJSON("index.php?q=churchresource/ajax", { func: "getMasterData" }, function (b) { timers.endMasterdata = new Date; masterData = b; b.version != churchresource_js_version && alert("Achtung, Versionen unterscheiden sich, bitte Cache loeschen! php:" + b.version + "/js:" + churchresource_js_version); churchInterface.clearStatus(); a != null && a() }) } function cr_mapJsonBookings(a) { booking = {}; booking.id = a.id; booking.resource_id = a.resource_id; booking.person_id = a.person_id; booking.person_name = a.person_name; booking.startdate = a.startdate.toDateEn(); booking.enddate = a.enddate.toDateEn(); booking.repeat_id = a.repeat_id; booking.repeat_frequence = a.repeat_frequence; booking.repeat_until = a.repeat_until; if (a.repeat_until != null) booking.repeat_until = a.repeat_until.toDateEn(); booking.repeat_option_id = a.repeat_option_id; booking.status_id = a.status_id; booking.text = a.text; booking.location = a.location; booking.note = a.note; booking.exceptions = a.exceptions; booking.additions = a.additions; booking.show_in_churchcal_yn = a.show_in_churchcal_yn; booking.cc_cal_id = a.cc_cal_id; booking.category_id = a.category_id; return booking } function cr_loadBookings(a) { churchInterface.setStatus("Lade Buchungen..."); timers.startAllPersons = new Date; churchInterface.jsonRead( { func: "getBookings" }, function (b) { timers.endAllPersons = new Date; jQuery.each(b, function (d, c) { allBookings[c.id] = cr_mapJsonBookings(c) }); churchInterface.clearStatus(); a != null && a() }) };
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var vehicleRepairItem_1 = require("./vehicleRepairItem"); var itemFactory_1 = require("./../../itemFactory"); var itemFactoryManager = require("./../../../managers/itemFactoryManager"); var SmallWrenchItem = (function (_super) { __extends(SmallWrenchItem, _super); function SmallWrenchItem() { var _this = _super.call(this) || this; _this.repairAmount = 20; _this.name = "Small Wrench"; _this.defaultSlots = [ [1, 1], ]; return _this; } return SmallWrenchItem; }(vehicleRepairItem_1.VehicleRepairItem)); exports.SmallWrenchItem = SmallWrenchItem; itemFactoryManager.add(SmallWrenchItem.name, "default", new itemFactory_1.ItemFactory(function () { return new SmallWrenchItem(); }));
'use strict'; var fs = require('fs-extra'); var ng = require('../helpers/ng'); var existsSync = require('exists-sync'); var expect = require('chai').expect; var forEach = require('lodash/forEach'); var walkSync = require('walk-sync'); var Blueprint = require('ember-cli/lib/models/blueprint'); var path = require('path'); var tmp = require('../helpers/tmp'); var root = process.cwd(); var util = require('util'); var conf = require('ember-cli/tests/helpers/conf'); var EOL = require('os').EOL; var path = require('path'); var Promise = require('ember-cli/lib/ext/promise'); describe('Acceptance: ng generate component', function() { before(conf.setup); after(conf.restore); beforeEach(function() { return tmp.setup('./tmp') .then(function() { process.chdir('./tmp'); }) .then(function(){ return ng([ 'new', 'foo', '--skip-npm', '--skip-bower' ]); }); }); afterEach(function() { this.timeout(10000); // return tmp.teardown('./tmp'); }); it('ng generate component my-comp', function() { return ng([ 'generate', 'component', 'my-comp' ]) .then(_ => { var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', 'my-comp', 'my-comp.ts'); expect(existsSync(testPath)).to.equal(true); }); }); it('ng generate component test' + path.sep + 'my-comp', function() { return ng([ 'generate', 'component', 'test' + path.sep + 'my-comp' ]) .then(_ => { var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', 'test', 'my-comp', 'my-comp.ts'); expect(existsSync(testPath)).to.equal(true); }); }); it('ng generate component test' + path.sep + '..' + path.sep + 'my-comp', function() { return ng([ 'generate', 'component', 'test' + path.sep + '..' + path.sep + 'my-comp' ]) .then(_ => { var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', 'my-comp', 'my-comp.ts'); expect(existsSync(testPath)).to.equal(true); }); }); it('ng generate component my-comp from a child dir', () => { return new Promise(function (resolve, reject) { process.chdir('./src'); resolve(); }) .then(_ => process.chdir('./app')) .then(_ => fs.mkdirsSync('./1')) .then(_ => process.chdir('./1')) .then(_ => { process.env.CWD = process.cwd(); return ng([ 'generate', 'component', 'my-comp' ]) }) .then(_ => { var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', '1', 'my-comp', 'my-comp.ts'); expect(existsSync(testPath)).to.equal(true); }, err => console.log('ERR: ', err)); }); it('ng generate component child-dir' + path.sep + 'my-comp from a child dir', () => { return new Promise(function (resolve, reject) { process.chdir('./src'); resolve(); }) .then(_ => process.chdir('./app')) .then(_ => fs.mkdirsSync('./1')) .then(_ => process.chdir('./1')) .then(_ => { process.env.CWD = process.cwd(); return ng([ 'generate', 'component', 'child-dir' + path.sep + 'my-comp' ]) }) .then(_ => { var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', '1', 'child-dir', 'my-comp', 'my-comp.ts'); expect(existsSync(testPath)).to.equal(true); }, err => console.log('ERR: ', err)); }); it('ng generate component child-dir' + path.sep + '..' + path.sep + 'my-comp from a child dir', () => { return new Promise(function (resolve, reject) { process.chdir('./src'); resolve(); }) .then(_ => process.chdir('./app')) .then(_ => fs.mkdirsSync('./1')) .then(_ => process.chdir('./1')) .then(_ => { process.env.CWD = process.cwd(); return ng([ 'generate', 'component', 'child-dir' + path.sep + '..' + path.sep + 'my-comp' ]) }) .then(_ => { var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', '1', 'my-comp', 'my-comp.ts'); expect(existsSync(testPath)).to.equal(true); }, err => console.log('ERR: ', err)); }); it('ng generate component ' + path.sep + 'my-comp from a child dir, gens under ' + path.join('src', 'app'), () => { return new Promise(function (resolve, reject) { process.chdir('./src'); resolve(); }) .then(_ => process.chdir('./app')) .then(_ => fs.mkdirsSync('./1')) .then(_ => process.chdir('./1')) .then(_ => { process.env.CWD = process.cwd(); return ng([ 'generate', 'component', path.sep + 'my-comp' ]) }) .then(_ => { var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', 'my-comp', 'my-comp.ts'); expect(existsSync(testPath)).to.equal(true); }, err => console.log('ERR: ', err)); }); it('ng generate component ..' + path.sep + 'my-comp from root dir will fail', () => { return ng([ 'generate', 'component', '..' + path.sep + 'my-comp' ]) .then(_ => { var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', '..', 'my-comp', 'my-comp.ts'); expect(existsSync(testPath)).to.equal(false); }); }); });
module.exports = { "type": "object", "properties": { "private_auction": { "type": "integer" }, "deals": { "type": "array", "items": { "type": "object" } }, "ext": { "type": "object" } } };
import React from 'react'; import { Link } from 'react-router'; class SocialPanelComponent extends React.Component { constructor (props) { super(props); // Only proceed if we have a specified social platform and handle given as a property if (this.props.platform === 'undefined' || this.props.handle === 'undefined') { return false; } } getUrlPrefix (platform) { let urlPrefix = ''; if (platform === 'facebook') { urlPrefix = 'https://www.facebook.com/'; } if (platform === 'instagram') { urlPrefix = 'https://www.instagram.com/'; } if (platform === 'snapchat') {} if (platform === 'twitter') { urlPrefix = 'https://twitter.com/'; } if (platform === 'youtube') { urlPrefix = 'https://youtube.com/'; } return urlPrefix; } render() { // Get the desired URL prefix based on the platform specified const urlPrefix = this.getUrlPrefix(this.props.platform); // Return the component markup return ( <Link className={"social-panel social-panel--" + this.props.platform} target="_blank" to={urlPrefix + this.props.handle} title={"Link to club " + this.props.platform + " page"}> <div className="social-panel__meta"> <span className="social-panel__platform">{this.props.platform}</span> <span className="social-panel__handle">{this.props.handle}</span> </div> </Link> ) } } export default SocialPanelComponent;
var EnhancedListingView = Marionette.View.extend({ events: { 'click [data-order]': 'changeOrder' }, collectionEvents: { 'meta:change:order_field meta:change:order_direction': 'renderOrder' }, initialize: function () { Marionette.View.prototype.initialize.call(this) this.$searchEl = this.options.searchEl this.$paginationContainerEl = this.options.paginationContainerEl this.feedbackView = this.options.feedbackView this.collectionViewClass = this.options.collectionViewClass || Marionette.CollectionView this.collection = new (this.options.collectionClass || ListingCollection) this.collection.url = this.$el.data('url') this.collection.meta.set(this.$el.data('initial-listing-data'), { silent: true }) this.listenTo(this.collection, 'request', this.loading) this.listenTo(this.collection, 'sync', this.loaded) this.listenTo(this.collection, 'error', this.error) this.configureCollectionView() this.configurePager() this.configureSearch() }, configureCollectionView: function () { this.collectionView = new this.collectionViewClass({ collection: this.collection }) this.$el.html(this.collectionView.$el) }, configurePager: function() { if (this.$paginationContainerEl) { this.pagerView = new PagerView({ model: this.collection.meta, labels: this.$paginationContainerEl.data('labels') }) this.$paginationContainerEl.html(this.pagerView.render().$el) } }, configureSearch: function () { if (this.$searchEl) { this.$searchEl.searchableField().on('searchable.search', _(this.search).bind(this)) } }, render: function () { this.bindUIElements() this.collectionView.render() return this }, loading: function () { this.$el.loadingOverlay('show') }, loaded: function () { this.$el.loadingOverlay('hide') if (this.feedbackView) { this.feedbackView.close() } }, error: function (model, jqXHR) { if (this.feedbackView && jqXHR.statusText !== 'abort') { this.feedbackView.render(this.$el.data('error-message'), 'alert-error', true) this.$el.loadingOverlay('hide') } }, search: function(e, term) { this.collection.meta.set({ term: term, current_page: 1 }) }, changeOrder: function (event) { var order = $(event.currentTarget).data('order') this.collection.meta.changeOrder(order) }, renderOrder: function () { var meta = this.collection.meta this.$('[data-order]').removeClass('selected asc desc') this.$('[data-order="' + meta.get('order_field') + '"]') .addClass('selected ' + meta.get('order_direction')) } }) // Listing Table marionette views var ListingTableEmptyView = Marionette.ItemView.extend({ tagName: 'tr', template: "[data-template-name=listing-table-empty-view]" }) var ListingTableItemView = Marionette.ItemView.extend({ tagName: 'tr', template: "[data-template-name=listing-table-item-view]" }) var ListingTableCompositeView = Marionette.CompositeView.extend({ tagName: 'table', className: '.table .table-striped', itemViewContainer: 'tbody', template: "[data-template-name=listing-table-composite-view]", itemView: ListingTableItemView, emptyView: ListingTableEmptyView })
var child_process = require('child_process'); var Promise = require('promise'); // Convert certificate to pem // openssl x509 -in website_aps_production.cer -inform DER -out website_aps_production.pem -outform PEM // Create p12 key // ["pkcs12", "-export", "-inkey", "web.net.openright.webpush.key", "-in", "website_aps_productio.pem", "-out", "website_aps_production.p12"], // Create signature file // ["smime", "-sign", "-signer", "website_aps_production.pem", "-inkey", "web.net.openright.webpush.key", "-nodetach", "-outform", "DER"] var execFile = Promise.denodeify(child_process.execFile); //var certificate = "website_aps_production.pem"; var certificate = "website_aps_production.pem"; var key = "web.net.openright.webpush.key"; var file = "manifest.json"; var output = "signature"; execFile("openssl", ["smime", "-sign", "-signer", certificate, "-inkey", key, "-in", file, "-binary", "-outform", "DER","-out", output], {}, function(err, stdout, stderr) { console.log("done", stdout, stderr); });
/** * filter Task * This is the main task that is invoked for the processing of the slushfile.js */ (function() { var gulp = require('gulp'), install = require('gulp-install'), conflict = require('gulp-conflict'), template = require('gulp-template'), rename = require('gulp-rename'), inquirer = require('inquirer') _ = require('underscore.string'); //Local dependencies var util = require('../util'); module.exports = function(gulp) { 'use strict'; gulp.task('filter', function(done) { var _this = this; var name = util.getDefaultOption(_this.args, 0); var options = util.getGlobalOptions(); var modules = util.getModuleProposal(options.appDir); if (modules.length === 0) { throw new Error('filter must be created in a module, but no modules exist. Create a module using "slush angular-gulp:module <module-Name>".'); } inquirer.prompt([{ type: 'input', name: 'fileName', message: 'What is the name of your filter?', default: name }, { type: 'list', name: 'module', message: 'What is your AngularJS module name?', choices: modules }, { type: 'confirm', name: 'test', message: 'Do you want to include unit testing?', default: true }], function(answers) { //Init answers.nameDashed = _.slugify(util.getNameProposal()); answers.scriptAppName = _.camelize(answers.nameDashed) + '.' +answers.module ; answers.classedName = _.camelize(answers.fileName); answers.classedNameDashed = _.slugify(answers.fileName); // test if (answers.test) { gulp.src(__dirname + '/../templates/filter/filter.spec.js') .pipe(template(answers)) .pipe(rename(answers.fileName + '-filter.spec.js')) .pipe(conflict(options.base + options.appDir + '/components/' + answers.module)) .pipe(gulp.dest(options.base + options.appDir + '/components/' + answers.module)) } //Source gulp.src(__dirname + '/../templates/filter/filter.js') .pipe(template(answers)) .pipe(rename(answers.fileName + '-filter.js')) .pipe(conflict(options.base + options.appDir + '/components/' + answers.module)) .pipe(gulp.dest(options.base + options.appDir + '/components/' + answers.module)) .on('finish', function() { done(); }); }); }); } })();
(function(global) { 'use strict'; var Util = (function() { return { /** * Appends new link tags to head which contain locations of extension * stylesheets. Allows override of page styles with !important marker. */ injectLinks: function(locations) { locations.forEach(function(location){ var head = document.head; var link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = chrome.extension.getURL( 'content_scripts/' + location + '.css'); head.appendChild(link); }); }, // Requests view from within chrome extension. getView: function(location, callback) { var viewPathName = '/content_scripts/' + location + '.html'; var extLocation = chrome.extension.getURL(viewPathName); var request = new XMLHttpRequest(); request.open('GET', extLocation, true); request.onload = function() { if (request.status >= 200 && request.status < 400) { callback(request.responseText); } else { console.log('Unable to get resource from Google Music Amplify' + 'extension'); } }; request.onerror = function() { console.log('Unable to contact Google Music Amplify extension'); }; request.send(); } }; })(); // Expose module to the global object global.Util = Util; })(this);
import axios from 'axios'; import AV from './AV'; import getCheerio from '../getCheerio'; import retryAxios from '../utils/retryAxios'; export default class Avgle extends AV { constructor() { super(); this.source = 'avgle'; this.baseURL = 'https://avgle.com'; this.http = axios.create({ baseURL: this.baseURL, timeout: 10000, }); } _getAllPagesUrls = async () => { const searchUrls = new Set(); let maxPageNum = 1; try { const { data } = await retryAxios(() => this.http.get(`/videos?o=mr&page=${maxPageNum}`) ); const $ = getCheerio(data); $('a').each((i, e) => { const url = $(e).attr('href') || ''; const match = url.match(/.*\/videos\?o=mr&page=(\d+)/); if (match && +match[1] > maxPageNum) { maxPageNum = +match[1]; } }); for (let i = 1, len = maxPageNum / 100; i <= len; i += 1) { searchUrls.add(`/videos?o=mr&page=${i}`); } } catch (err) { console.error(`err message: ${err.message}`); console.error(`error at ${this.source} axios.get`); } return searchUrls; }; }
var Waterline = require('../../../lib/waterline'), assert = require('assert'); describe('.beforeCreate()', function() { describe('basic function', function() { var person; before(function(done) { var waterline = new Waterline(); var Model = Waterline.Collection.extend({ identity: 'user', connection: 'foo', attributes: { name: 'string' }, beforeCreate: function(values, cb) { values.name = values.name + ' updated'; cb(); } }); waterline.loadCollection(Model); // Fixture Adapter Def var adapterDef = { create: function(con, col, values, cb) { return cb(null, values); }}; var connections = { 'foo': { adapter: 'foobar' } }; waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) { if(err) done(err); person = colls.collections.user; done(); }); }); /** * Create */ describe('.create()', function() { it('should run beforeCreate and mutate values', function(done) { person.create({ name: 'test' }, function(err, user) { assert(!err); assert(user.name === 'test updated'); done(); }); }); }); }); /** * Test Callbacks can be defined as arrays and run in order. */ describe('array of functions', function() { var person; before(function(done) { var waterline = new Waterline(); var Model = Waterline.Collection.extend({ identity: 'user', connection: 'foo', attributes: { name: 'string' }, beforeCreate: [ // Function 1 function(values, cb) { values.name = values.name + ' fn1'; cb(); }, // Function 2 function(values, cb) { values.name = values.name + ' fn2'; cb(); } ] }); waterline.loadCollection(Model); // Fixture Adapter Def var adapterDef = { create: function(con, col, values, cb) { return cb(null, values); }}; var connections = { 'foo': { adapter: 'foobar' } }; waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) { if(err) done(err); person = colls.collections.user; done(); }); }); it('should run the functions in order', function(done) { person.create({ name: 'test' }, function(err, user) { assert(!err); assert(user.name === 'test fn1 fn2'); done(); }); }); }); });
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react') const CompLibrary = require('../../core/CompLibrary.js') const { MarkdownBlock, GridBlock, Container } = CompLibrary /* Used to read markdown */ const siteConfig = require(`${process.cwd()}/siteConfig.js`) function docUrl(doc, language) { return `${siteConfig.baseUrl}${language ? `${language}/` : ''}${doc}` } function imgUrl(img) { return `${siteConfig.baseUrl}img/${img}` } class Button extends React.Component { render() { return ( <div className="pluginWrapper buttonWrapper"> <a className="button hero" href={this.props.href} target={this.props.target} > {this.props.children} </a> </div> ) } } Button.defaultProps = { target: '_self' } const SplashContainer = props => ( <div className="homeContainer"> <div className="homeSplashFade"> <div className="wrapper homeWrapper">{props.children}</div> </div> </div> ) const Logo = props => ( <div className="projectLogo"> <img src={props.img_src} alt="Project Logo" /> </div> ) const ProjectTitle = () => ( <React.Fragment> <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }} > <img src={'img/redux.svg'} alt="Redux logo" width={100} height={100} /> <h1 className="projectTitle">{siteConfig.title}</h1> </div> <h2 style={{ marginTop: '0.5em' }}>Official React bindings for Redux</h2> </React.Fragment> ) const PromoSection = props => ( <div className="section promoSection"> <div className="promoRow"> <div className="pluginRowBlock">{props.children}</div> </div> </div> ) class HomeSplash extends React.Component { render() { const language = this.props.language || '' return ( <SplashContainer> <div className="inner"> <ProjectTitle /> <PromoSection> <Button href={docUrl('introduction/quick-start', language)}> Get Started </Button> </PromoSection> </div> </SplashContainer> ) } } const Block = props => ( <Container id={props.id} background={props.background} className={props.className} > <GridBlock align="center" contents={props.children} layout={props.layout} /> </Container> ) const FeaturesTop = props => ( <Block layout="fourColumn" className="featureBlock"> {[ { content: 'React Redux is maintained by the Redux team, and **kept up-to-date with the latest APIs from Redux and React**.', image: imgUrl('noun_Certificate_1945625.svg'), imageAlign: 'top', title: 'Official' }, { content: "**Designed to work with React's component model**. You define how to extract the values your component needs from Redux, and your component receives them as props.", image: imgUrl('noun_Check_1870817.svg'), imageAlign: 'top', title: 'Predictable' }, { content: "Creates wrapper components that **manage the store interaction logic for you**, so you don't have to write it yourself.", image: imgUrl('noun_Box_1664404.svg'), imageAlign: 'top', title: 'Encapsulated' }, { content: 'Automatically implements **complex performance optimizations**, so that your own component only re-renders when the data it needs has actually changed.', image: imgUrl('noun_Rocket_1245262.svg'), imageAlign: 'top', title: 'Optimized' } ]} </Block> ) const OtherLibraries = props => ( <Block layout="twoColumn" className="libBlock"> {[ { content: 'A predictable state container for JavaScript applications', title: '[Redux ![link2](img/external-link-square-alt-solid.svg)](https://redux.js.org) ' }, { content: 'The official, opinionated, batteries-included toolset for efficient Redux development', title: '[Redux Toolkit ![link2](img/external-link-square-alt-solid.svg)](https://redux-toolkit.js.org)' } ]} </Block> ) class Index extends React.Component { render() { const language = this.props.language || '' return ( <div> <div style={{ background: '#111', padding: '10px 0', lineHeight: 2 }}> <div className="container"> <div style={{ color: 'white', fontWeight: 'bold', textAlign: 'center' }} > Black Lives Matter. <a style={{ display: 'inline-block', color: 'white', fontWeight: 'bold', margin: '0 10px', padding: '7px 20px', border: '1px solid white' }} href="https://support.eji.org/give/153413" target="_blank" rel="noopener noreferrer" > Support the Equal Justice Initiative. </a> </div> </div> </div> <HomeSplash language={language} /> <div className="mainContainer"> <div className="productShowcaseSection"> <Container background="light"> <FeaturesTop /> </Container> <Container> <h2 style={{ marginTop: '0.5em' }}> Other Libraries from the Redux Team </h2> <OtherLibraries /> </Container> </div> </div> </div> ) } } module.exports = Index
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var event = require('./util-event'); (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object') { window.event = factory(); } })(function () { return event; }); },{"./util-event":2}],2:[function(require,module,exports){ 'use strict'; var event = { bind: function bind(element, name, listener) { element.addEventListener(name, listener, false); }, unbind: function unbind(element, name, listener) { element.removeEventListener(name, listener, false); }, once: function once(element, name, listener) { var that = this; var once = function once(e) { that.unbind(element, name, once); listener(e); }; that.bind(element, name, once); } }; module.exports = event; },{}]},{},[1]);