text
stringlengths
2
6.14k
require('babel-core/register') const path = require('path') const jsdom = require('jsdom').jsdom const exposedProperties = ['window', 'navigator', 'document'] global.document = jsdom('') global.window = document.defaultView Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property) global[property] = document.defaultView[property] } }) global.navigator = { userAgent: 'node.js' } global.__base = `${path.resolve()}/`
module.exports = (client, reaction, user) => { client.log('Log', `${user.tag} reagiu à mensagem de id ${reaction.message.id} com a reação: ${reaction.emoji}`); };
const exec = require('child_process').exec; const ver = require('../package.json').version; let hash; module.exports.init = function (b) { exec('git rev-parse HEAD', (error, stdout, stderr) => { if (error != null) { hash = null; console.err("git's broken yo"); } hash = stdout; }); }; module.exports.run = function (r, parts, reply) { reply(`${ver}: ${hash}`); }; module.exports.commands = ['version'];
(function () { function getQueryVariable(variable) { var query = window.location.search.substring(1), vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] === variable) { return pair[1]; } } } function getPreview(query, content, previewLength) { previewLength = previewLength || (content.length * 2); var parts = query.split(" "), match = content.toLowerCase().indexOf(query.toLowerCase()), matchLength = query.length, preview; // Find a relevant location in content for (var i = 0; i < parts.length; i++) { if (match >= 0) { break; } match = content.toLowerCase().indexOf(parts[i].toLowerCase()); matchLength = parts[i].length; } // Create preview if (match >= 0) { var start = match - (previewLength / 2), end = start > 0 ? match + matchLength + (previewLength / 2) : previewLength; preview = content.substring(start, end).trim(); if (start > 0) { preview = "..." + preview; } if (end < content.length) { preview = preview + "..."; } // Highlight query parts preview = preview.replace(new RegExp("(" + parts.join("|") + ")", "gi"), "<strong>$1</strong>"); } else { // Use start of content if no match found preview = content.substring(0, previewLength).trim() + (content.length > previewLength ? "..." : ""); } return preview; } function displaySearchResults(results, query) { var searchResultsEl = document.getElementById("search-results"), searchProcessEl = document.getElementById("search-process"); if (results.length) { var resultsHTML = ""; results.forEach(function (result) { var item = window.data[result.ref], contentPreview = getPreview(query, item.content, 170), titlePreview = getPreview(query, item.title); resultsHTML += "<li><h4><a href='" + item.url.trim() + "'>" + titlePreview + "</a></h4><p><small>" + contentPreview + "</small></p></li>"; }); searchResultsEl.innerHTML = resultsHTML; searchProcessEl.innerText = "Exibindo"; } else { searchResultsEl.style.display = "none"; searchProcessEl.innerText = "No"; } } window.index = lunr(function () { this.field("id"); this.field("title", {boost: 10}); this.field("date"); this.field("url"); this.field("content"); }); var query = decodeURIComponent((getQueryVariable("q") || "").replace(/\+/g, "%20")), searchQueryContainerEl = document.getElementById("search-query-container"), searchQueryEl = document.getElementById("search-query"); searchQueryEl.innerText = query; searchQueryContainerEl.style.display = "inline"; for (var key in window.data) { window.index.add(window.data[key]); } displaySearchResults(window.index.search(query), query); // Hand the results off to be displayed })();
import UnitConverter from '../../../UnitConverter' import { Fraction, mul, div } from '../../../../numbers' import { Mass } from '../../domains' import { UnitedStates } from '../../authorities' import { OunceConverter } from '../../us/customary/mass' import { ChickenEggs } from '../../systems' import { Jumbo, VeryLarge, Large, Medium, Small, Peewee } from '../../units' const jumboScalar = new Fraction(5, 2) export const JumboConverter = new UnitConverter( Mass, UnitedStates, ChickenEggs, Jumbo, OunceConverter, value => mul(value, jumboScalar), value => div(value, jumboScalar)) const veryLargeScalar = new Fraction(9, 4) export const VeryLargeConverter = new UnitConverter( Mass, UnitedStates, ChickenEggs, VeryLarge, OunceConverter, value => mul(value, veryLargeScalar), value => div(value, veryLargeScalar)) const largeScalar = 2 export const LargeConverter = new UnitConverter( Mass, UnitedStates, ChickenEggs, Large, OunceConverter, value => mul(value, largeScalar), value => div(value, largeScalar)) const mediumScalar = new Fraction(7, 4) export const MediumConverter = new UnitConverter( Mass, UnitedStates, ChickenEggs, Medium, OunceConverter, value => mul(value, mediumScalar), value => div(value, mediumScalar)) const smallScalar = new Fraction(3, 2) export const SmallConverter = new UnitConverter( Mass, UnitedStates, ChickenEggs, Small, OunceConverter, value => mul(value, smallScalar), value => div(value, smallScalar)) const peeweeScalar = new Fraction(5, 4); export const PeeweeConverter = new UnitConverter( Mass, UnitedStates, ChickenEggs, Peewee, OunceConverter, value => mul(value, peeweeScalar), value => div(value, peeweeScalar)) export function collectUnitConverters() { return [ JumboConverter, VeryLargeConverter, LargeConverter, MediumConverter, SmallConverter, PeeweeConverter ] }
'use strict'; var path = require('path'); var generators = require('yeoman-generator'); var yaml = require('js-yaml'); var _ = require('lodash'); var chalk = require('chalk'); var GitHub = require('github'); module.exports = generators.Base.extend({ _logHeading: function (msg) { this.log("\n"); this.log.writeln(chalk.bold(msg)); this.log.writeln(chalk.bold('-------------------------------')); }, _listPlugins: function () { var github = new GitHub({ version: '3.0.0' }); github.search.repos({ q: 'wok-plugin+in:name' }, function (err, response) { console.log(response.items.length); }); }, // The name `constructor` is important here constructor: function () { // Calling the super constructor is important so our generator is correctly set up generators.Base.apply(this, arguments); this.answers = {}; }, askForProject: function () { var done = this.async(); var _utils = this._; this._logHeading('Collecting new project infos...'); var prompts = [{ type: 'text', name: 'name', message: 'Project name', 'default': 'awesome-wok-project', filter: function (value) { return _utils.slugify(value) } }, { type: 'text', name: 'description', message: 'Project description', 'default': 'Awesome WOK Project' }, { type: 'text', name: 'author', message: 'Author', 'default': this.user.git.name() }, { type: 'text', name: 'license', message: 'License', 'default': 'MIT' }]; this.prompt(prompts, function (answers) { this.answers.projectData = answers; done(); }.bind(this)); }, askForFolders: function () { var done = this.async(); var _utils = this._; this._logHeading('Filesystem setup...'); var prompts = [ { type: 'text', name: 'www', message: 'Public assets folder', 'default': 'www', filter: function (value) { return _utils.slugify(value) } }]; this.prompt(prompts, function (answers) { answers.rsync = answers.www; this.answers.folders = answers; done(); }.bind(this)); }, fetchRepo: function () { var done = this.async(); this.remote('fevrcoding', 'wok', 'master', function (err, remote, files) { if (err) { //TODO manage error this.log.error('Unable to download latest version of https://github.com/fevrcoding/wok'); return false; } this.wokRepo = remote; this.wokFiles = files; done(); }.bind(this)); //this._listPlugins(); }, copyFiles: function () { var remote = this.wokRepo; var files = this.wokFiles; //copy main application folder remote.directory('application', 'application'); //build folder remote.dest.mkdir('build'); //copy unchanged configuration files ['hosts.yml', 'properties.yml'].forEach(function (filename) { var fullpath = path.join('build', 'grunt-config', filename); remote.copy(fullpath, fullpath); }); //copy unchanged files ['build/Gruntfile.js', 'build/compass.rb', 'bower.json', 'Gemfile'].forEach(function (filepath) { remote.copy(filepath, filepath); }); //copy dot files files.filter(function (path) { return path.indexOf('.') === 0 && path !== '.bowerrc'; }).forEach(function (el) { remote.copy(el, el); }); }, package: function () { var pkg = this.wokRepo.src.readJSON('package.json'); pkg = _.extend(pkg || {}, { version: '0.0.1', contributors: [] }, this.answers.projectData); this.wokRepo.dest.write('package.json', JSON.stringify(pkg, null, 4)); return pkg; }, config: function (remote) { var remote = this.wokRepo; var pathCfg = yaml.safeLoad(remote.src.read('build/grunt-config/paths.yml')); var defaultPublic = pathCfg.www; pathCfg = _.extend(pathCfg, this.answers.folders); remote.dest.write('build/grunt-config/paths.yml', yaml.safeDump(pathCfg)); //public www data to destination public folder remote.directory(defaultPublic, pathCfg.www); //write .bowerrc remote.dest.write('.bowerrc', JSON.stringify({directory: pathCfg.www + '/vendor'}, null, 4)); return pathCfg; }, readme: function () { //generate an empty readme file this.wokRepo.dest.write('README.md', '#' + this.answers.projectDescription + "\n\n"); }, install: function () { if (!this.options['skip-install']) { this.spawnCommand('bundler', ['install']); this.installDependencies({ skipMessage: true }); } var template = _.template('\n\nI\'m all done. ' + '<%= skipInstall ? "Just run" : "Running" %> <%= commands %> ' + '<%= skipInstall ? "" : "for you " %>to install the required dependencies.' + '<% if (!skipInstall) { %> If this fails, try running the command yourself.<% } %>\n\n' ); this.log(template({ skipInstall: this.options['skip-install'], commands: chalk.yellow.bold(['bower install', 'npm install', 'bundler install'].join(' & ')) })); } });
class MetaFloorController extends MRM.MetaBaseWallController{ constructor(dom){ super(dom); this.dom = dom; this.metaObject = this.createMetaObject() this.metaVerse = null; this.setupComponent(); this.updateMetaObject(); } get metaAttachedActions(){ return { attachMetaObject: true, assignRoomDimension: true } } get propertiesSettings(){ return { width: { type: Number, default: 1 }, length: { type: Number, default: 1 }, roomWidth: { type: Number, default: 1, onChange: "updateMetaObject" }, roomHeight: { type: Number, default: 1, onChange: "updateMetaObject" }, roomLength: { type: Number, default: 1, onChange: "updateMetaObject" } }; } get tagName() { return "meta-floor" } get metaChildrenNames(){ return ["meta-table", "meta-picture", "meta-text", "meta-board", "meta-item"] } get eventActionSettings(){ return { "meta-style": ['propagateMetaStyle'], "class": ["propagateMetaStyle"], "id": ["propagateMetaStyle"] } } updateMetaObject() { var mesh = this.metaObject.mesh; var group = this.metaObject.group; this.properties.width = this.properties.roomWidth; this.properties.length = this.properties.roomLength; group.rotation.x = 270 * (Math.PI/180); group.position.set(0, 0 , 0); mesh.scale.set(this.properties.roomWidth, this.properties.roomLength , 1); this.updateChildrenDisplayInline(); } } class MetaFloor extends MRM.MetaComponent { createdCallback() { this.controller = new MetaFloorController(this); super.createdCallback(); } metaDetached(e) { var targetController = e.detail.controller; if (this.controller.isChildren(targetController.tagName) ){ e.stopPropagation(); this.controller.metaObject.group.remove(targetController.metaObject.group); } } metaChildAttributeChanged(e){ var targetController = e.detail.controller; var attrName = e.detail.attrName if (this.controller.isChildren(targetController.tagName) ){ if(targetController.isAllowedAttribute(attrName)) { if (e.detail.actions.updateChildrenDisplayInline) { this.controller.updateChildrenDisplayInline() delete e.detail.actions.updateChildrenDisplayInline } } } } } document.registerElement('meta-floor', MetaFloor);
import 'isomorphic-fetch' import base64 from 'base-64' import utf8 from 'utf8' import Request from './Request' function encodeAccount(username, password) { let bytes = utf8.encode(`${ username }:${ password }`) return base64.encode(bytes) } export default class Stormpath { constructor({ application, authentication } = {}) { this.application = application this.authentication = authentication } retrieveApplication() { let url = `https://api.stormpath.com/v1/applications/${ this.application }/accounts` let options = { authentication: this.authentication } return Request.get(url, options) } createAccount(payload) { let url = `https://api.stormpath.com/v1/applications/${ this.application }/accounts` let options = { authentication: this.authentication, payload: payload } return Request.post(url, options) } retrieveAccount(account) { let url = `https://api.stormpath.com/v1/accounts/${ account }` let options = { authentication: this.authentication } return Request.get(url, options) } authenticateAccount({ username, password } = {}) { let url = `https://api.stormpath.com/v1/applications/${ this.application }/loginAttempts` //url = 'http://requestb.in/uwektzuw' let payload = { type: 'basic', value: encodeAccount(username, password) } let options = { authentication: this.authentication, payload: payload } return Request.post(url, options) } } if (require.main === module) { const credentials = { application: 'zDhRIszpk93AwssJDXuPs', authentication: { username: '1HU99B538PG3SW50K5M2NPJBW', password: '7ukbB9oDRjgyMEX/057SKtAwwLtOR3fbKvNQOp4i/uI' } } const account = { givenName: 'Denis', surname: 'Storm', username: 'DenisCarriere', email: 'foo.bar2@gmail.com', password: 'Denis44C', customData: { number: 4 } } const stormpath = new Stormpath(credentials) //stormpath.createAccount(account) //stormpath.retrieveApplication() stormpath.authenticateAccount(account) stormpath.retrieveAccount('3NElH12QutCmRSi3e6PAmI') .then( data => console.log(data), error => console.log(error) ) }
/* global Fae, SimpleMDE, toolbarBuiltInButtons */ /** * Fae form text * @namespace form.text * @memberof form */ Fae.form.text = { init: function() { this.overrideMarkdownDefaults(); this.initMarkdown(); }, /** * Override SimpleMDE's preference for font-awesome icons and use a modal for the guide * @see {@link modals.markdownModal} */ overrideMarkdownDefaults: function() { toolbarBuiltInButtons['bold'].className = 'icon-bold'; toolbarBuiltInButtons['italic'].className = 'icon-italic'; toolbarBuiltInButtons['heading'].className = 'icon-font'; toolbarBuiltInButtons['code'].className = 'icon-code'; toolbarBuiltInButtons['unordered-list'].className = 'icon-list-ul'; toolbarBuiltInButtons['ordered-list'].className = 'icon-list-ol'; toolbarBuiltInButtons['link'].className = 'icon-link'; toolbarBuiltInButtons['image'].className = 'icon-image'; toolbarBuiltInButtons['quote'].className = 'icon-quote'; toolbarBuiltInButtons['fullscreen'].className = 'icon-fullscreen no-disable no-mobile'; toolbarBuiltInButtons['horizontal-rule'].className = 'icon-minus'; toolbarBuiltInButtons['preview'].className = 'icon-eye no-disable'; toolbarBuiltInButtons['side-by-side'].className = 'icon-columns no-disable no-mobile'; toolbarBuiltInButtons['guide'].className = 'icon-question'; // Override SimpleMDE's default guide and use a homegrown modal toolbarBuiltInButtons['guide'].action = Fae.modals.markdownModal; }, /** * Find all markdown fields and initialize them with a markdown GUI * @has_test {features/form_helpers/fae_input_spec.rb} */ initMarkdown: function() { $('.js-markdown-editor:not(.mde-enabled)').each(function() { var $this = $(this); var editor = new SimpleMDE({ element: this, autoDownloadFontAwesome: false, status: false, spellChecker: false, hideIcons: ['image', 'side-by-side', 'fullscreen', 'preview'] }); // Disable tabbing within editor editor.codemirror.options.extraKeys['Tab'] = false; editor.codemirror.options.extraKeys['Shift-Tab'] = false; $this.addClass('mde-enabled'); // code mirror events to hook into current form element functions editor.codemirror.on('change', function(){ // updates the original textarea's value for JS validations $this.val(editor.value()); // update length counter Fae.form.validator.length_counter.updateCounter($this); }); editor.codemirror.on('focus', function(){ $this.parent().addClass('mde-focus'); }); editor.codemirror.on('blur', function(){ // trigger blur on the original textarea to trigger JS validations $this.blur(); $this.parent().removeClass('mde-focus'); }); }); } };
'use babel'; // eslint-disable-next-line import { CompositeDisposable, TextEditor, Directory } from 'atom'; import config from './config'; import Creator from './Creator'; import Insertor from './Insertor'; class DavsPackage { constructor() { this.reactReduxUtilsView = null; this.modalPanel = null; this.subscriptions = null; this.config = config; } activate() { // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable this.subscriptions = new CompositeDisposable(); this.creator = new Creator(); this.insertor = new Insertor(); // Register command that toggles this view this.subscriptions.add(atom.commands.add('atom-workspace', { 'davs-package:create': context => this.create(context), 'davs-package:insert': context => this.insert(context), 'core:confirm': (event) => { this.creator.confirmSelection(); event.stopPropagation(); }, })); } deactivate() { this.subscriptions.dispose(); } create(context) { this.creator.create(context); } insert() { this.insertor.insert(); } } export default new DavsPackage();
import React from 'react'; import PropTypes from 'prop-types'; import Text from '../Text/Text'; import { Styled } from './CalloutGroupItem.styles'; const CalloutGroupItem = ({ text, imgSrc, imgAlt, emoji }) => { return ( <> {!imgSrc ? ( !emoji ? ( <Text>{text}</Text> ) : ( <Text> <Styled.CalloutGroupItemTool> <Styled.CalloutGroupItemEmoji role="img" aria-label={imgAlt}> {emoji} </Styled.CalloutGroupItemEmoji> {text} </Styled.CalloutGroupItemTool> </Text> ) ) : ( <Text> <Styled.CalloutGroupItemTool> <Styled.CalloutGroupItemLogo src={imgSrc} alt={imgAlt} aria-label={imgAlt} /> {text} </Styled.CalloutGroupItemTool> </Text> )} </> ); }; CalloutGroupItem.defaultProps = { imgSrc: null, imgAlt: null, emoji: null, }; CalloutGroupItem.propTypes = { emoji: PropTypes.string, text: PropTypes.oneOfType([PropTypes.node, PropTypes.string]).isRequired, imgSrc: PropTypes.node, imgAlt: PropTypes.string, }; export default CalloutGroupItem;
// Render home page and json data exports.view = function(req, res){ // Import json data var logData = require("../data/log.json"); // Set ateFoodGroup to numerical values var ateGrains; if(req.body.ateGrains == null){ateGrains = 0;} else ateGrains = 1; var ateFruit; if(req.body.ateFruit == null){ateFruit = 0;} else ateFruit = 1; var ateDairy; if(req.body.ateDairy == null){ateDairy = 0;} else ateDairy = 1; var ateProtein; if(req.body.ateProtein == null){ateProtein = 0;} else ateProtein = 1; var ateVeggies; if(req.body.ateVeggies == null){ateVeggies = 0;} else ateVeggies = 1; // Creat new JSON and append to log var newLog = { "id": logData.length + 1, "name": req.body.food, "dd": req.body.dd, "mm": req.body.mm, "year": req.body.yy, "cal": parseInt(req.body.cal), "mood": parseInt(req.body.mood), "info": req.body.info, "image": "public/images/food/oj.jpg", "ateGrains": ateGrains, "ateFruit": ateFruit, "ateVeggies": ateVeggies, "ateProtein": ateProtein, "ateDairy": ateDairy } logData.push(newLog); var newData = JSON.stringify(logData); var fs = require('fs'); fs.writeFile("data/log.json",newData, function(err) { if(err) { return console.log(err); } console.log("The new log was saved!"); res.redirect('/vet'); }); };
var expect = require('expect.js'); var Promise = require('bluebird'); var ZugZug = require('../lib/zugzug'); var Job = require('../lib/job'); describe('job.delete():Promise(self)', function() { var zz, job; beforeEach(function() { zz = new ZugZug(); job = new Job(zz, 'default'); }); afterEach(function(done) { Promise.promisify(zz._client.flushall, zz._client)() .then(zz.quit.bind(zz)) .done(function() {done();}); }); it('returns a promise', function(done) { job.save() .then(function() { var p = job.delete(); expect(p).to.be.a(Promise); return p.thenReturn(); }) .done(done); }); it('resolves to the instance', function(done) { job.save() .then(function() { return job.delete(); }) .then(function(res) { expect(res).to.equal(job); }) .done(done); }); it('deletes the job from the database', function(done) { var id; job.save() .then(function() { expect(job.id).to.equal('1'); id = job.id; return job.delete(); }) .then(function() { return zz.getJob(id); }) .then(function(res) { expect(res).to.equal(null); }) .done(done); }); it('resets the job\'s state', function(done) { job.save() .then(function() { return job.delete(); }) .then(function() { expect(job.id).to.be(undefined); expect(job.created).to.be(undefined); expect(job.updated).to.be(undefined); expect(job.state).to.be(undefined); }) .done(done); }); it('deletes the job\'s log', function(done) { var id; job.save() .then(function() { expect(job.id).to.equal('1'); id = job.id; return job.delete(); }) .then(function() { var m = zz._client.multi() .llen('zugzug:job:' + id + ':log'); return Promise.promisify(m.exec, m)(); }) .spread(function(newlen) { expect(newlen).to.equal(0); }) .done(done); }); });
'use strict'; module.exports = { app: { title: 'Surf Around The Corner', description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js', keywords: 'MongoDB, Express, AngularJS, Node.js' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/components-font-awesome/css/font-awesome.css', 'public/lib/angular-ui-select/dist/select.css', 'http://fonts.googleapis.com/css?family=Bree+Serif', 'http://fonts.googleapis.com/css?family=Open+Sans', 'http://fonts.googleapis.com/css?family=Playfair+Display', 'http://fonts.googleapis.com/css?family=Dancing+Script', 'http://fonts.googleapis.com/css?family=Nunito' //'http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css' ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/jquery/dist/jquery.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js', 'public/lib/angular-ui-select/dist/select.js', 'public/lib/ng-lodash/build/ng-lodash.js', 'public/lib/ng-backstretch/dist/ng-backstretch.js', 'public/lib/ngFitText/src/ng-FitText.js' ] }, css: [ 'public/less/*.css', 'public/modules/**/css/*.css' ], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
"use strict";var assert;module.watch(require('assert'),{default(v){assert=v}},0);var unhexArray;module.watch(require('./testutil'),{unhexArray(v){unhexArray=v}},1);var table;module.watch(require('../src/table'),{default(v){table=v}},2); describe('table.js', function() { it('should make a ScriptList table', function() { // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Examples 1 & 2 var expectedData = unhexArray( '0003 68616E69 0014 6B616E61 0020 6C61746E 002E' + // Example 1 (hani, kana, latn) '0004 0000 0000 FFFF 0001 0003' + // hani lang sys '0004 0000 0000 FFFF 0002 0003 0004' + // kana lang sys '000A 0001 55524420 0016' + // Example 2 for latn '0000 FFFF 0003 0000 0001 0002' + // DefLangSys '0000 0003 0003 0000 0001 0002' // UrduLangSys ); assert.deepEqual(new table.ScriptList([ { tag: 'hani', script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [3] }, langSysRecords: [] } }, { tag: 'kana', script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [3, 4] }, langSysRecords: [] } }, { tag: 'latn', script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [0, 1, 2] }, langSysRecords: [{ tag: 'URD ', langSys: { reserved: 0, reqFeatureIndex: 3, featureIndexes: [0, 1, 2] } }] } }, ]).encode(), expectedData); }); });
/*jshint node:true */ module.exports = function( grunt ) { "use strict"; var entryFiles = grunt.file.expandFiles( "entries/*.xml" ); grunt.loadNpmTasks( "grunt-clean" ); grunt.loadNpmTasks( "grunt-wordpress" ); grunt.loadNpmTasks( "grunt-jquery-content" ); grunt.loadNpmTasks( "grunt-check-modules" ); grunt.initConfig({ clean: { folder: "dist" }, lint: { grunt: "grunt.js" }, xmllint: { all: [].concat( entryFiles, "categories.xml", "entries2html.xsl" ) }, xmltidy: { all: [].concat( entryFiles, "categories.xml" ) }, "build-pages": { all: grunt.file.expandFiles( "pages/**" ) }, "build-xml-entries": { all: entryFiles }, "build-resources": { all: grunt.file.expandFiles( "resources/**" ) }, wordpress: grunt.utils._.extend({ dir: "dist/wordpress" }, grunt.file.readJSON( "config.json" ) ), watch: { scripts: { files: 'entries/*.xml', tasks: ['wordpress-deploy'], options: { interrupt: true } } } }); grunt.registerTask( "default", "build-wordpress" ); grunt.registerTask( "build", "build-pages build-xml-entries build-xml-categories build-xml-full build-resources" ); grunt.registerTask( "build-wordpress", "check-modules clean lint xmllint build" ); grunt.registerTask( "tidy", "xmllint xmltidy" ); };
var searchData= [ ['slot_5fcount',['SLOT_COUNT',['../classmastermind_1_1_mastermind.html#ad4cfc8127641ff8dfe89d65ae232331c',1,'mastermind::Mastermind']]] ];
(function() { var AS = this, Fn = AS.Fn; // assign $.extend(Fn, { execConvPrint: execConvPrint }); return; function execConvPrint() { var b_FPR = AS.Bo.FPR; var fn = null; try { if(b_FPR.Value('convfn') == "function(i, f, a){\n}") throw Error('Function is not modified'); fn = eval('(' + (b_FPR.Value('convfn') || null) + ')'); if(typeof fn != 'function') throw Error('Not function.'); } catch(e) { return b_FPR.error(e); } if(execConvPrint.last) // TODO remove console.log(execConvPrint.last); var fncs = b_FPR.Value('items[func]'); var args = b_FPR.Value('items[args]'); var memo = {}; fncs.forEach(function(func, i) { var a = null; try { a = eval('(' + args[i] + ')'); } catch(e) { return console.log('JSON.parse fail No.' + i, args[i]); } var nval = fn.call(b_FPR, i, func, $.extend(true, [], a)); nval && (function() { console.log('changing idx[' + i + ']', a, nval); b_FPR.Value('items[args][' + i + ']', JSON.stringify(nval)); memo[i] = {}, memo[i].func = func, memo[i].args = a; })(); }); execConvPrint.last = memo; b_FPR.notice('変換完了', Fn.noticeOpt()); } }).call(window.AppSpace);
const gulp = require('gulp'); const spawn = require('../lib/spawn'); const config = require('../config'); gulp.task('webpack', (callback) => { if (config.context === 'production') { process.env.NODE_ENV = 'production'; } process.env.WEBPACK_CONTEXT = config.context; const options = []; if (config.context === 'watch') { options.push('-w'); } spawn('node_modules/.bin/webpack', options, callback); });
module.exports = { attributes: { group: { model: 'Group' }, user: { model: 'User' }, synchronized: 'boolean', active: 'boolean', child_group: { model: 'Group' }, level: 'integer' }, migrate: 'safe', tableName: 'all_membership_group', autoUpdatedAt: false, autoCreatedAt: false };
var Type = require("@kaoscript/runtime").Type; module.exports = function() { let tt = foo(); if(!Type.isValue(tt)) { tt = bar; } };
'use strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var TaskSchema = new Schema({ name: String, description: String, point: Number, task_users: [{ type: Schema.Types.ObjectId, ref: "TaskUser"}], _week: { type: Schema.Types.ObjectId, ref: "Week"} }); module.exports = mongoose.model('Task', TaskSchema);
'use strict'; // prePublish gets run on 'npm install' (e.g. even if you aren't actually publishing) // so we have to check to make sure that we are in our own directory and this isn't // some poor user trying to install our package. var path = require('path'); var fs = require('fs'); var rootDirectory = path.join(__dirname, "../../"); if (path.basename(rootDirectory) != "Thali_CordovaPlugin") { process.exit(0); } var readMeFileName = "readme.md"; var parentReadMe = path.join(__dirname, "../../", readMeFileName); var localReadMe = path.join(__dirname, "../", readMeFileName); fs.writeFileSync(localReadMe, fs.readFileSync(parentReadMe)); process.exit(0);
import React, { Component } from 'react'; import classnames from 'classnames'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import LinearProgress from 'material-ui/LinearProgress'; import history from '../../core/history'; import Link from '../../components/Link/Link'; import Image from '../../components/Image'; import { Grid, Row, Col, ListGroup, ListGroupItem } from 'react-bootstrap'; import { AutoAffix } from 'react-overlays'; import s from './SystemsList.css'; import configs from '../../config/systems.json'; const System = ({name, title, image, available, visible, onClick}) => { const classNames = classnames(s.availabilityCheckIcon, "fa", available ? 'fa-check' : 'fa-close', available ? s.available : s.unavailable); return ( <div key={`system-${name}`} className={classnames(s.system, !visible ? s.hidden : s.show )} onClick={() => onClick(`/system/${name}`)} > <Image src={image} alt={title} /> <div className={s.systemTitle}>{title}</div> <i className={classNames} /> </div> ) }; class Systems extends Component { constructor(...props) { super(...props); this.state = { show: 'available' }; this.onHandleClick = ::this.onHandleClick; this.filter = ::this.filter; } onHandleClick(url) { history.push(url); } filter(system) { const { checkList } = this.props; if (this.state.show == 'all') { return true; } else if (this.state.show == 'available' && checkList[system.name]) { return true; } else if (this.state.show == 'not_available' && !checkList[system.name]) { return true; } return false; } setFilter(filter) { this.setState({ show: filter }); } renderSystems() { const { isChecking, checkList } = this.props; if (isChecking || checkList == undefined) { return (<LinearProgress />); } return ( <Row className={s.list}> <Col xs={12} md={8}> { configs.map((system) => { const isAvailable = checkList[system.name]; const isVisible = this.filter(system); return ( <System key={`emu-${system.name}`} {...system} available={isAvailable} visible={isVisible} onClick={this.onHandleClick} /> ) }) } </Col> <Col xs={6} md={3}> <AutoAffix viewportOffsetTop={15} container={this}> <ListGroup> <ListGroupItem onClick={this.setFilter.bind(this, 'available')} active={this.state.show == 'available'} > Show only available systems </ListGroupItem> <ListGroupItem onClick={this.setFilter.bind(this, 'not_available')} active={this.state.show == 'not_available'} > Show only not available systems </ListGroupItem> <ListGroupItem onClick={this.setFilter.bind(this, 'all')} active={this.state.show == 'all'} > Show all systems </ListGroupItem> </ListGroup> </AutoAffix> </Col> </Row> ); } render() { return ( <div className={s.container}> <h1>Systems</h1> <Grid> {this.renderSystems()} </Grid> </div> ) } } export default withStyles(s)(Systems);
version https://git-lfs.github.com/spec/v1 oid sha256:32728342485677be1fe240941c1404f53f367f741f7980cf29ae5c77e3f66a16 size 558
var Accumulator, errorTypes, isConstructor, isType, isValidator, throwFailedValidator, throwFailure, throwInvalidType; throwFailure = require("failure").throwFailure; Accumulator = require("accumulator"); isConstructor = require("./isConstructor"); isValidator = require("./isValidator"); errorTypes = require("../errorTypes"); isType = require("./isType"); module.exports = function(value, type, key) { var relevantData, result; if (isConstructor(key, Object)) { relevantData = key; key = relevantData.key; } else { relevantData = { key: key }; } if (!type) { throwFailure(Error("Must provide a 'type'!"), { value: value, type: type, key: key, relevantData: relevantData }); } if (isValidator(type)) { result = type.validate(value, key); if (result !== true) { throwFailedValidator(type, result, relevantData); } } else if (!isType(value, type)) { throwInvalidType(type, value, relevantData); } }; throwFailedValidator = function(type, result, relevantData) { var accumulated; accumulated = Accumulator(); accumulated.push(result); if (relevantData) { accumulated.push(relevantData); } return type.fail(accumulated.flatten()); }; throwInvalidType = function(type, value, relevantData) { var accumulated, error; accumulated = Accumulator(); accumulated.push({ type: type, value: value }); if (relevantData) { accumulated.push(relevantData); } error = errorTypes.invalidType(type, relevantData.key); return throwFailure(error, accumulated.flatten()); }; //# sourceMappingURL=../../../map/src/core/assertType.map
import SyncClient from 'sync-client'; const versions = [{ version: 1, stores: { bookmarks: 'id, parentID', folders: 'id, parentID', }, }, { version: 2, stores: { bookmarks: 'id, parentID, *tags', folders: 'id, parentID', tags: 'id', }, }]; export default new SyncClient('BookmarksManager', versions); export { SyncClient };
'use strict'; angular.module('meanDemoApp') .config(function ($stateProvider) { $stateProvider .state('main', { url: '/', templateUrl: 'app/main/main.html', controller: 'MainCtrl' }); });
const _parseHash = function (hash) { let name = ''; let urlType = ''; let hashParts = hash.split('_'); if (hashParts && hashParts.length === 2) { name = hashParts[1]; let type = hashParts[0]; // take off the "#" let finalType = type.slice(1, type.length); switch (finalType) { case 'method': urlType = 'methods'; break; case 'property': urlType = 'properties'; break; case 'event': urlType = 'events'; break; default: urlType = ''; } return { urlType, name, }; } return null; }; function hashToUrl(window) { if (window && window.location && window.location.hash) { let hashInfo = _parseHash(window.location.hash); if (hashInfo) { return `${window.location.pathname}/${hashInfo.urlType}/${hashInfo.name}?anchor=${hashInfo.name}`; } } return null; } function hasRedirectableHash(window) { let canRedirect = false; if (window && window.location && window.location.hash) { let hashParts = window.location.hash.split('_'); if (hashParts && hashParts.length === 2) { canRedirect = true; } } return canRedirect; } export { hashToUrl, hasRedirectableHash };
/** * An ES6 screeps game engine. * * An attempt to conquer screeps, the first MMO strategy sandbox * game for programmers! * * @author Geert Hauwaerts <geert@hauwaerts.be> * @copyright Copyright (c) Geert Hauwaerts * @license MIT License */ /** * Cache for static function results. */ export default class Cache { /** * Cache for static function results. * * @returns {void} */ constructor() { this.cache = {}; } /** * Store or retrieve an entry from cache. * * @param {string} table The cache table. * @param {string} key The entry to store or retrieve. * @param {*} value The callback function. * @param {*} ...args The callback function arguments. * @returns {*} */ remember(table, key, callback, ...args) { if (this.cache[table] === undefined) { this.cache[table] = {}; } let value = this.cache[table][key]; if (value === undefined) { value = callback(args); this.cache[table][key] = value; } return value; } /** * Remove an entry from cache. * * @param {string} table The cache table. * @param {string} key The entry to remove. * @returns {void} */ forget(table, key) { delete this.cache[table][key]; } }
'use strict'; var conf = require('../config'); var ctrlBuilder = require('../controllers/face-controller'); var version = conf.get('version'); var base_route = conf.get('baseurlpath'); var face_route = base_route + '/face'; module.exports = function (server, models, redis) { var controller = ctrlBuilder(server, models, redis); server.get({path: face_route, version: version}, controller.randomFace); server.head({path: face_route, version: version}, controller.randomFace); };
var chai = require('chai'); chai.use(require('chai-fs')); var expect = chai.expect var execute = require('../'); describe('execute', function() { it('should exist', function() { expect(execute).to.exist; }); it('should return a promise', function() { expect(execute().then).to.exist; }); it('should return an result object handed through it', function(done) { var result = { key: 'val' } execute(result).then(function(res) { if (res) { expect(res).to.equal(result); done(); } else { done(new Error('Expected result to be resolved')); } }, function() { done(new Error('Expected function to resolve, not reject.')); }); }); describe('shell commands', function() { it('should execute a string as a shell script', function(done) { //Test by creating file and asserting that it exists execute(null, { shell: 'echo "new file content" >> ./test/file.txt' }).then(function(){ expect("./test/file.txt").to.be.a.file("file.txt not found") done() }, function() { done(new Error('expected function to resolve, not reject')); }) //Remove file and asserting that it does not exist execute(null, { shell: 'rm ./test/file.txt' }).then(function(){ expect("./test/file.txt").not.to.be.a.file("file.txt not found") done() }, function() { done(new Error('expected function to resolve, not reject')); }) }); }); describe('bash scripts', function() { it('should execute a file as a bash script', function(done) { //Test by creating file and asserting that it exists execute(null, { bashScript: './test/test-script' }).then(function(){ expect("./test/file.txt").to.be.a.file("file.txt not found") done() }, function() { done(new Error('expected function to resolve, not reject')); }) //Remove file and asserting that it does not exist execute(null, { shell: 'rm ./test/file.txt' }).then(function(){ expect("./test/file.txt").not.to.be.a.file("file.txt not found") done() }, function() { done(new Error('expected function to resolve, not reject')); }); }); it('should hand parameters to bash scripts', function(done) { //Test by creating file and asserting that it exists execute(null, { bashScript: './test/test-script-params', bashParams: ['./test/file.txt'] }).then(function(){ expect("./test/file.txt").to.be.a.file("file.txt not found") done() }, function() { done(new Error('expected function to resolve, not reject')); }) //Remove file and asserting that it does not exist execute(null, { shell: 'rm ./test/file.txt' }).then(function(){ expect("./test/file.txt").not.to.be.a.file("file.txt not found") done() }, function() { done(new Error('expected function to resolve, not reject')); }) }); }); xdescribe('logging', function() { //TODO: enforce this: these two log tests could be enforced with an abstracted log func and a spy.... it('should default logging to false', function() { execute(null, { shell: 'echo "i should not log"' }).then(function(){ done() }, function() { done(new Error('expected function to resolve, not reject')); }) }); //TODO: enforce this it('should allow toggling logging', function() { execute(null, { logOutput: true, shell: 'echo "i should log"' }).then(function(){ done() }, function() { done(new Error('expected function to resolve, not reject')); }) }); }); });
/* * catberry-homepage * * Copyright (c) 2015 Denis Rechkunov and project contributors. * * catberry-homepage's license follows: * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * This license applies to all parts of catberry-homepage that are not * externally maintained libraries. */ 'use strict'; module.exports = Overview; var util = require('util'), StaticStoreBase = require('../../lib/StaticStoreBase'); util.inherits(Overview, StaticStoreBase); /* * This is a Catberry Store file. * More details can be found here * https://github.com/catberry/catberry/blob/master/docs/index.md#stores */ /** * Creates new instance of the "static/Quotes" store. * @constructor */ function Overview() { StaticStoreBase.call(this); } Overview.prototype.filename = 'github/overview';
import util from './util' import LatLngBounds from './latlngbounds' const {abs, max, min, PI, sin, cos, acos} = Math const rad = PI / 180 // distance between two geographical points using spherical law of cosines approximation function distance (latlng1, latlng2) { const lat1 = latlng1.lat * rad const lat2 = latlng2.lat * rad const a = sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos((latlng2.lng - latlng1.lng) * rad) return 6371000 * acos(min(a, 1)); } class LatLng { constructor(a, b, c) { if (a instanceof LatLng) { return a; } if (Array.isArray(a) && typeof a[0] !== 'object') { if (a.length === 3) { return this._constructor(a[0], a[1], a[2]) } if (a.length === 2) { return this._constructor(a[0], a[1]) } return null; } if (a === undefined || a === null) { return a } if (typeof a === 'object' && 'lat' in a) { return this._constructor(a.lat, 'lng' in a ? a.lng : a.lon, a.alt); } if (b === undefined) { return null; } return this._constructor(a, b, c) } _constructor(lat, lng, alt) { if (isNaN(lat) || isNaN(lng)) { throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')'); } // @property lat: Number // Latitude in degrees this.lat = +lat // @property lng: Number // Longitude in degrees this.lng = +lng // @property alt: Number // Altitude in meters (optional) if (alt !== undefined) { this.alt = +alt } } // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overriden by setting `maxMargin` to a small number. equals(obj, maxMargin) { if (!obj) { return false } obj = new LatLng(obj); const margin = max(abs(this.lat - obj.lat), abs(this.lng - obj.lng)) return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin); } // @method toString(): String // Returns a string representation of the point (for debugging purposes). toString(precision) { return `LatLng(${this.lat.toFixed(precision)}, ${this.lng.toFixed(precision)})` } // @method distanceTo(otherLatLng: LatLng): Number // Returns the distance (in meters) to the given `LatLng` calculated using the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula). distanceTo(other) { return distance(this, new LatLng(other)) } // @method wrap(): LatLng // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees. wrap(latlng) { const lng = util.wrapNum(latlng.lng, [-180, 180], true) return new LatLng(latlng.lat, lng, latlng.alt) } // @method toBounds(sizeInMeters: Number): LatLngBounds // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters` meters apart from the `LatLng`. toBounds(sizeInMeters) { const latAccuracy = 180 * sizeInMeters / 40075017 const lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat) return LatLngBounds( [this.lat - latAccuracy, this.lng - lngAccuracy], [this.lat + latAccuracy, this.lng + lngAccuracy] ) } clone() { return new LatLng(this.lat, this.lng, this.alt) } } module.exports = LatLng
import React from 'react' const EditableText = React.createClass({ propTypes: { onSubmit: React.PropTypes.func.isRequired, validator: React.PropTypes.func, enableEditing: React.PropTypes.bool, value: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, ]) }, getInitialState: function() { return { editing: false, invalid: false, newValue: this.props.value, }; }, getDefaultProps: function() { return { enableEditing: true }; }, edit() { this.setState({editing: true}); }, handleChange(e) { this.setState({newValue: e.target.value}); }, cancelEdit() { this.setState({ editing: false, invalid: false, }); }, submit(e) { e.preventDefault(); if (!this.props.validator || this.props.validator(this.state.newValue)) { this.props.onSubmit(this.state.newValue); this.cancelEdit(); } else { this.setState({invalid: true}); } }, renderInputForm() { const inputForm = ( <form onSubmit={this.submit} className={this.state.invalid ? 'has-error' : ''} > <input type="text" autoFocus onChange={this.handleChange} onBlur={this.cancelEdit} value={this.state.newValue} className="form-control inline-editable" /> </form> ); return inputForm; }, render: function() { if (this.props.enableEditing) { return ( <div className="inline-edit"> {this.state.editing ? this.renderInputForm() : <a onClick={this.edit} title="Edit" className={'inline-editable'}>{this.props.value || 'Add'}</a> } </div> ); } else { return (<span>{this.props.value}</span>); } } }); export default EditableText
(function () { "use strict"; //angular.module('app', ['angularUtils.directives.dirPagination']); var env = {}; if (window) { Object.assign(env, window.__env); } var app = angular.module("deviceManagement", ['angularUtils.directives.dirPagination', 'common.services', 'ui.router'//, //'deviceResourceRest' //'deviceResourceMock' ]); app.constant("rootUrl", "http://www.example.com"); app.constant("$env", env); // configure state for device list // add route state // reference the app variable app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { // pass in $stateProvider - and use array to be min safe $urlRouterProvider.otherwise("/"); //("/devices"); // default otherwise if an activated state has no entry $stateProvider .state("home", { url: "/", templateUrl: "app/welcomeView.html" }) //manifest .state("manifestList", { url: "/devices/manifest/:DeviceId", templateUrl: "app/devices/manifestList.html", controller: "ManifestCtrl as vm" }) //devices .state("deviceList", { // set url fragment url: "/devices", // http://localhost:8000/#/devices templateUrl: "app/devices/deviceListView.html", // url location fetched template from web server controller: "DeviceListCtrl as vm" // associated controller is contructed }) .state("deviceEdit", { abstract: true, // abstract set so that it cannot be explicitly activated , it must have child state url: "/devices/edit/:DeviceId", // param is required which specific device id templateUrl: "app/devices/deviceEditView.html", // ui elements controller: "DeviceEditCtrl as vm", // as with alias of vm // resolve: { // deviceResource: "deviceResource", // device: function (deviceResource, $stateParams) { // var DeviceId = $stateParams.DeviceId; // return deviceResource.get({ DeviceId: DeviceId }).$promise; // } // } }) .state("deviceEdit.info", { url: "/info", templateUrl: "app/devices/deviceEditInfoView.html" }) .state("deviceEdit.price", { url: "/price", templateUrl: "app/devices/deviceEditPriceView.html" }) .state("deviceEdit.tags", { url: "/tags", templateUrl: "app/devices/deviceEditTagsView.html" }) .state("deviceDetail", { url: "/devices/:DeviceId", // param is required which specific device id templateUrl: "app/devices/deviceDetailView.html", // ui elements controller: "DeviceDetailCtrl as vm"//{ //$scope.DeviceId = $stateParams.DeviceId; //var DeviceId = $stateParams.DeviceId; //} //controller: "DeviceDetailCtrl as vm" //, // as with alias of vm // resolve: { // resolve is a property of the stateconfiguration object // deviceResource: "deviceResource", // key value pair Key is deviceResource value is string name of "deviceResource" // device: function (deviceResource, $stateParams) { // $stateParams service is needed because url: has this :DeviceId // var DeviceId = $stateParams.DeviceId; // return deviceResource.get({ DeviceId: DeviceId }).$promise; // function returns the promise // } // } }) //console.log('end .state ui router'); }] ); } ());
/** * Created by zad on 17/4/20. */ /** to left shift an Array * @param {Array} arr * @param {Number} num * @return {Array} */ function leftShift(arr, num) { const result = arr.concat(); if (num < 0) { return rightShift(arr, -num); } while (num > 0) { result.push(result.shift()); num--; } return result; } /** to right shift an Array * @param {Array} arr * @param {Number} num * @return {Array} */ function rightShift(arr, num) { return leftShift(arr, arr.length - num); } export {leftShift, rightShift};
/* eslint-env node */ 'use strict'; module.exports = { 'cowsay': require('./cowsay') };
module.exports = { Server: app => ({ app, listen: jest.fn(), }), };
/* global bp, noEvents, emptySet */ /* * This little app adds bthreads dynamically. */ bp.log.info("Program Loaded"); // Define the events. var kidADone = bp.Event("kidADone"); var kidBDone = bp.Event("kidBDone"); var parentDone = bp.Event("parentDone"); bp.registerBThread("parentBThread", function () { bp.log.info("parent started"); // first one, text for behavior on the start() method. bp.registerBThread( "kid a1", function() { bp.log.info("kid a1 started"); bp.sync({request:kidADone, block:parentDone}); }); bp.registerBThread( "kid b1", function() { bp.log.info("kid b1 started"); bp.sync({request:kidBDone, block:parentDone}); }); bp.sync( {request: parentDone} ); // second round, test for behavior on the resume() method. bp.registerBThread( "kid a2", function() { bp.sync({request:kidADone, block:parentDone}); }); bp.registerBThread( "kid b2", function() { bp.sync({request:kidBDone, block:parentDone}); }); bp.sync( {request: parentDone} ); });
//configure requirejs var requirejs = require('requirejs'); requirejs.config({ baseUrl: __dirname + '/../javascripts', nodeRequire: require }); //turn off rendering for commandline unit tests var global = requirejs('global'); global.RENDER = false; //export requirejs module.exports = { require: requirejs };
"use strict" /** * Construct URL for Magento Admin. * * @param {string} path path to Magento page (absolute path started with '/', alias - w/o) */ var result = function getUrl(path) { /* shortcuts for globals */ var casper = global.casper; var mobi = global.mobi; var root = mobi.opts.navig.mage; /* functionality */ casper.echo(" construct Magento Admin URL for path '" + path + "'.", "PARAMETER"); var isAlias = path.indexOf('/') === -1; // absolute path contains at least one '/' char var result, url; if (isAlias) { /* compose URI based on "route.to.page" */ var route = mobi.objPath.get(root.admin, path); url = route.self; } else { /* absolute path is used */ url = path } /* "http://mage2.local.host.com" + "/admin" + "url" */ result = root.self + root.admin.self + url; casper.echo(" result URL: " + result, "PARAMETER"); return result; } module.exports = result;
"use strict"; module.exports = function (context) { return context.data.root.query.name + context.data.root.query.suffix; };
/** * @author mrdoob / http://mrdoob.com/ */ var Config = function () { var namespace = 'threejs-inspector'; var storage = { 'selectionBoxEnabled': false, 'rafEnabled' : false, 'rafFps' : 30, } if ( window.localStorage[ namespace ] === undefined ) { window.localStorage[ namespace ] = JSON.stringify( storage ); } else { var data = JSON.parse( window.localStorage[ namespace ] ); for ( var key in data ) { storage[ key ] = data[ key ]; } } return { getKey: function ( key ) { return storage[ key ]; }, setKey: function () { // key, value, key, value ... for ( var i = 0, l = arguments.length; i < l; i += 2 ) { storage[ arguments[ i ] ] = arguments[ i + 1 ]; } window.localStorage[ namespace ] = JSON.stringify( storage ); console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' ); }, clear: function () { delete window.localStorage[ namespace ]; } } };
var _ = require("underscore"); var util = require("util"); exports.show = function (req, res) { var async = require('async'); if (!req.session.screen) { req.session.messages = { errors: ['screen not found'] }; res.redirect('/'); return; } var Handlebars = require('../hbs_helpers/hbs_helpers.js'); var fs = require('fs'); var JSONParse = require('json-literal-parse'); var screen = req.session.screen; var arr_widgetHTML = []; var widgetUtil = require('../lib/widget_util.js'); async.each(screen.widgets, function (widget, cb) { widgetUtil.render_widget(widget, function (err, w_html) { if(!err) arr_widgetHTML.push(w_html); else{ console.log("Failed to render widget " + widget.id + " : "+ err); req.session.messages = { errors: ["Failed to render widget " + widget.id + " : "+ err ] }; } cb(null); }); }, function (err) { req.session.screen.widgets = arr_widgetHTML; var data = { username: req.session.user.username, title: 'Screen : '+req.session.screen.name, screens: req.session.screens, widgets: req.session.widgets, screen: req.session.screen }; res.render('screens/show', data); }); }; exports.new = function (req, res) { var data = { username: req.session.user.username, title: 'Screen : Create New', screens: req.session.screens, widgets:req.session.widgets }; res.render('screens/new', data); }; exports.create = function (req, res) { //Deny direct post request if (!req.body.hasOwnProperty('screen_name') || !req.body.hasOwnProperty('screen_desc')) { res.status(401); res.send('Unauthorized Access <a href=\'/screens/new\'>Create New Screen</a> '); return; } var t_screen = { name: req.body.screen_name, description: req.body.screen_desc, widgets : [] }; var Screen = require('../models/screen'); //Create new screen Screen.save( t_screen, function(err, screen){ if(!err){ console.log('Screen created successfully'); req.session.messages = { success: ['Screen(' + t_screen.name + ') created successfully'], errors: [] }; res.redirect('/screens/'+screen.id); return; }else{ console.log('Failed to create screen: ',err); req.session.messages = { validationErrors: err }; res.redirect('screens/new'); return; } }); }; exports.addWidget = function(req, res){ var data = { username: req.session.user.username, title: 'Screen : Create New', screens: req.session.screens, screen:req.session.screen, widgets:req.session.widgets }; res.render("screens/widgets/add", data) }; exports.updateWidgets = function(req, res){ // res.send("widgets size: " + req.body.widgets.length +" Instance of " +( req.body.widgets instanceof Array)) // return; var Screen = require("../models/screen.js") Screen.addWidgets(req.params.id, req.body.widgets, function(err, suc){ if(err){ console.log("Error adding widgets to the screen: ", err); req.session.messages = { errors: ["Error adding widgets to the screen: " + err] }; res.redirect("/screens/"+req.params.id + "/widgets/add"); }else{ console.log(" Widgets added successfully!!") req.session.messages = { success: [ "Widgets added successfully!!"] }; res.redirect("/screens/"+req.params.id ); } }) } exports.removeWidget = function(req, res){ }; exports.delete = function (req, res) { if (!req.session.screen) { req.session.messages = { errors: ['screen not found'] }; } else { var Screen = require('../models/screen'); Screen.destroy(req.session.screen, function(err){ if(err){ util.log("Failed to delete screen "+err); req.session.messages = { errors: ['Failed to delete screen. ' + err] }; }else{ util.log("Screen deleted successfully"); req.session.messages = { success: ['Screen ' + req.session.screen.name + ' deleted successfully'] }; req.session.screen = null; } res.redirect('/'); return; }); } };
var db=require('./dbDatabase'); var mysql=require('mysql'); var connect_pool=mysql.createPool(db.options); connect_pool.connectionLimit=100; //准备好20个链接 connect_pool.queueLimit=100; //最大链接数 function getConnection(callback){ connect_pool.getConnection(function(err,client){ if(err){ console.log(err.message); setTimeout(getConnection,2000); } callback(client); }) } exports.getConnection=getConnection;
angular.module('factoria', ['firebase']) .factory('fireService', ['$firebaseArray', function($firebaseArray){ var firebaseRef= ""; var setFirebaseSource = function(url){ firebaseRef= new Firebase(url); }; var getFirebaseRoot = function(){ return firebaseRef; }; var addData = function(data){ // persist our data to firebase var ref = getFirebaseRoot(); return $firebase(ref).$push(data); }; var getData = function(callback){ var ref = getFirebaseRoot(); //TODO: //Call koaRender to update new elements style return $firebaseArray(ref); } var service = { setFirebaseSource : setFirebaseSource, addData : addData, getData : getData, getFirebaseRoot : getFirebaseRoot }; return service; }]);
const path = require('path'); const wmd = require('wmd'); const {getFile} = require('./importHelpers'); const createContextForList = (folderContents) => { let promises = []; return new Promise((resolve, reject) => { for (let file in folderContents) { let promise = getFile(folderContents[file].path); promises.push(promise); } Promise.all(promises).then(results => { for (let file in folderContents) { const content = wmd(results[file], { preprocessors: [wmd.preprocessors.metadata, wmd.preprocessors.fencedCodeBlocks] }); folderContents[file].meta = content.metadata; } resolve(folderContents); }); }); } // gets context data from file url - works both for list entries and pages const createContextFromFile = (fileUrl) => { return new Promise((resolve, reject) => { getFile(fileUrl).then(data => { const parsedData = { context: wmd(data, { preprocessors: [wmd.preprocessors.metadata, wmd.preprocessors.fencedCodeBlocks] }), fileName: path.parse(fileUrl).name, } resolve(parsedData); }); }); } module.exports.createContextForList = createContextForList; module.exports.createContextFromFile = createContextFromFile;
class AchievementEvt { constructor(subType, payload) { this.type = 'achievements'; this.subType = subType; this.payload = payload; } }; /** * generate PageVisitEvt * @param {string} * @returns {AchievementEvt} */ export class PageVisitEvt extends AchievementEvt { constructor(pageName) { super('page-visited', pageName); } }; /** * generate ForgotPasswordEvt * @param {String} targetEmail * @returns {AchievementEvt} */ export class ForgotPasswordEvt extends AchievementEvt { constructor(targetEmail) { super('forgot-password', targetEmail); } }; /** * generate ForgotPasswordEvt * @returns {AchievementEvt} */ export class MoodRegisteredEvt extends AchievementEvt { constructor() { super('mood-registered'); } }; /** * generate TimeTravelEvt * @param {Object} targetRange * @returns {AchievementEvt} */ export class TimeTravelEvt extends AchievementEvt { constructor(targetRange) { super('time-travel', targetRange); } }; // TODO // clickedOnNotification from SW - just after action [fast hand, tchin tchin, chain reaction] // ensure all ui event are processed - OK [mood entry, page visits, past, future, forgot password] await TEST [duck face] KO [duck face] // snackbar for achievements + animation const badgesConfig = { badgesArray: [ { title: 'adventurer', description: 'visited all pages in one session', badge: 'adventurer' }, { title: 'lost in translation', description: 'went to 404 page', badge: 'lost-in-translation' }, { title: 'duck face', description: 'got a custom avatar', badge: 'no-more-faceless' }, { title: 'goldfish', description: 'forgot password mechanism activated X1', badge: 'goldfish' }, { title: 'alzeihmer', description: 'forgot password mechanism activated X3', badge: '019-grandfather' }, { title: 'mood alert', description: 'subscribed for notifications', badge: '003-smartphone' }, { title: 'mood monitor', description: 'multiple subscriptions for notifications', badge: '010-technology' }, { title: 'fast hand', description: 'clicked on notification', badge: 'fast-hand' }, { title: 'tchin tchin', description: 'your mood update notification nudged someone else mood update', badge: '001-toast' }, { title: 'chain reaction', description: 'your mood update notification nudged two persons to update their mood', badge: '007-share' }, { title: 'back to the future', description: 'time traveled more than one month in the past', badge: 'back-to-the-future' }, { title: 'fortuneteller', description: 'tried to time travel more than a month in the future. Tip: it is useless!', badge: '010-crystal-ball' }, { title: 'noob moodist', description: 'first mood update', badge: '014-helmet' }, { title: 'baron moodist', description: 'updated mood three days straight', badge: '011-crown-2' }, { title: 'duke moodist', description: 'updated mood a full week straight', badge: '012-crown-1' }, { title: 'archduke moodist', description: 'updated mood a full month straight', badge: '010-crown-3' }, { title: 'king moodist', description: 'updated mood three months straight', badge: '013-crown' }, { title: 'emperor moodist', description: 'updated mood a full year straight', badge: '003-greek' }, { title: 'happy days', description: 'positive mood for the last five updates', badge: '005-heavy-metal' }, { title: 'depression', description: 'negative mood for the last five updates', badge: '006-crying' }, { title: 'zen & balanced', description: 'neurtral mood for the last three updates', badge: '003-libra' }, { title: 'mood roller coaster', description: 'changed mood from positive to negative, or reverse, in one day', badge: '005-roller-coaster' }, { title: 'mood swings meds', description: 'changed mood more than three times a day', badge: '008-pills' }, { title: 'blissed', description: 'mood updated to highest possible score', badge: '004-island' }, { title: 'suicidal tendencies', description: 'mood updated to lowest possible score', badge: '006-gallows' }, { title: 'come back', description: 'from negative to positive mood', badge: '005-profits' }, { title: 'mood swing', description: 'from positive to negative mood', badge: '004-loss' }, { title: 'stairway to heaven', description: 'mood increased 5 scores at once', badge: '015-paper-plane' }, { title: 'nuclear disaster', description: 'mood decreased 5 scores at once', badge: '007-bomb-detonation' } ], AchievementsEvts: { PageVisitEvt: PageVisitEvt, ForgotPasswordEvt: ForgotPasswordEvt, TimeTravelEvt: TimeTravelEvt, MoodRegisteredEvt: MoodRegisteredEvt }, technical: { gravatarImagesCacheName: '$$$toolbox-cache$$$https://moodies-1ad4f.firebaseapp.com/$$$', adventurerPageList: ['home', 'profile', 'users', 'mood-input', 'time-travel', 'about', 'badges'], adventurerID: 'adventurer', lostInTranslationPageList: ['404'], lostInTranslationID: 'lost in translation', backToTheFutureID: 'back to the future', fortunetellerID: 'fortuneteller', alzeihmerGoldfishID: 'forgotPasswordCounter', duckFaceID: 'duck face', moodsRelatedAchievementsSpecialEvt: 'all-moods-related-achievements' } }; export default badgesConfig;
function InputHandler(viewport) { var self = this; self.pressedKeys = {}; self.mouseX = 0; self.mouseY = 0; self.mouseDownX = 0; self.mouseDownY = 0; self.mouseMoved = false; self.mouseDown = false; self.mouseButton = 0; // 1 = left | 2 = middle | 3 = right self.viewport = viewport; var viewportElem = viewport.get(0); viewportElem.ondrop = function(event) { self.onDrop(event); }; viewportElem.ondragover = function(event) { event.preventDefault(); }; viewportElem.onclick = function(event) { self.onClick(event); }; viewportElem.onmousedown = function(event) { self.onMouseDown(event); }; window.onmouseup = function(event) { self.onMouseUp(event); }; window.onkeydown = function(event) { self.onKeyDown(event); }; window.onkeyup = function(event) { self.onKeyUp(event); }; window.onmousemove = function(event) { self.onMouseMove(event); }; viewportElem.oncontextmenu = function(event) { event.preventDefault();}; viewport.mousewheel(function(event) { self.onScroll(event); }); } InputHandler.prototype.update = function(event) { for(var key in this.pressedKeys) { this.target.onKeyDown(key); } }; InputHandler.prototype.onKeyUp = function(event) { delete this.pressedKeys[event.keyCode]; }; InputHandler.prototype.onKeyDown = function(event) { // Avoid capturing key events from input boxes and text areas var tag = event.target.tagName.toLowerCase(); if (tag == 'input' || tag == 'textarea') return; var keyCode = event.keyCode; this.pressedKeys[keyCode] = true; var ctrl = event.ctrlKey; this.target.onKeyPress(keyCode, ctrl); }; InputHandler.prototype.isKeyDown = function(key) { var isDown = this.pressedKeys[key] !== undefined; return isDown; }; // Return mouse position in [0,1] range relative to bottom-left of viewport (screen space) InputHandler.prototype.convertToScreenSpace = function(pageX, pageY) { var left = this.viewport.offset().left; var top = this.viewport.offset().top; var width = this.viewport.innerWidth(); var height = this.viewport.innerHeight(); var x = (pageX - left)/width; var y = -(pageY - top)/height + 1.0; return [x,y]; }; InputHandler.prototype.onDrop = function(event) { event.preventDefault(); var mouse = this.convertToScreenSpace(event.pageX, event.pageY); var assetName = event.dataTransfer.getData("text"); this.target.dropAsset(assetName, mouse[0], mouse[1]); }; InputHandler.prototype.onClick = function(event) { if(this.mouseMoved) return; var screenSpace = this.convertToScreenSpace(event.pageX, event.pageY); this.target.onClick(screenSpace[0], screenSpace[1]); }; InputHandler.prototype.onMouseDown = function(event) { this.viewport.focus(); if(this.mouseButton > 0) return; // Don't process a mouse down from a different button until the current one is done this.mouseButton = event.which; this.mouseDown = true; var mouseX = event.pageX; var mouseY = event.pageY; this.mouseDownX = mouseX; this.mouseDownY = mouseY; this.mouseMoved = false; var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseDown(screenSpace[0], screenSpace[1], this.mouseButton) }; InputHandler.prototype.onMouseUp = function(event) { this.mouseDown = false; this.mouseButton = 0; }; InputHandler.prototype.onMouseMove = function(event) { var mouseX = event.pageX; var mouseY = event.pageY; // Ignore click if mouse moved too much between mouse down and mouse click if(Math.abs(this.mouseDownX - mouseX) > 3 || Math.abs(this.mouseDownY - mouseY) > 3) { this.mouseMoved = true; } if(this.mouseDown) { event.preventDefault(); } var mouseMoveX = mouseX - this.mouseX; var mouseMoveY = mouseY - this.mouseY; this.mouseX = mouseX; this.mouseY = mouseY; var screenSpace = this.convertToScreenSpace(mouseX, mouseY); this.target.onMouseMove(screenSpace[0], screenSpace[1], mouseMoveX, mouseMoveY, this.mouseButton); }; InputHandler.prototype.onScroll = function(event) { this.target.onScroll(event.deltaY); };
const config = require('../../../knexfile').intweb const knex = require('knex')(config) const dateFormatter = require('../date-formatter') const insertClaimEvent = require('./insert-claim-event') const claimEventEnum = require('../../constants/claim-event-enum') module.exports = function (claimId, isTrusted, untrustedReason) { return getEligibilityData(claimId) .then(function (eligibilityData) { if (isTrusted !== eligibilityData.IsTrusted) { var updateObject = { isTrusted: isTrusted, UntrustedDate: !isTrusted ? dateFormatter.now().toDate() : null, UntrustedReason: !isTrusted ? untrustedReason : null } return knex('Eligibility') .where('EligibilityId', eligibilityData.EligibilityId) .update(updateObject) .then(function () { var event = isTrusted ? claimEventEnum.ALLOW_AUTO_APPROVAL.value : claimEventEnum.DISABLE_AUTO_APPROVAL.value return insertClaimEvent(eligibilityData.Reference, eligibilityData.EligibilityId, claimId, event, null, untrustedReason, null, true) }) } }) } function getEligibilityData (claimId) { return knex('Claim') .join('Eligibility', 'Claim.EligibilityId', '=', 'Eligibility.EligibilityId') .where('ClaimId', claimId) .first() .select('Eligibility.EligibilityId', 'Eligibility.Reference', 'Eligibility.IsTrusted') }
import Ember from 'ember'; import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'; import config from 'ilios/config/environment'; const { inject } = Ember; const { service } = inject; export default Ember.Route.extend(ApplicationRouteMixin, { flashMessages: service(), commonAjax: service(), i18n: service(), moment: service(), /** * Leave titles as an array * All of our routes send translations for the 'titleToken' key and we do the translating in head.hbs * and in the application controller. * @param Array tokens * @return Array */ title(tokens){ return tokens; }, //Override the default session invalidator so we can do auth stuff sessionInvalidated() { if (!Ember.testing) { let logoutUrl = '/auth/logout'; return this.get('commonAjax').request(logoutUrl).then(response => { if(response.status === 'redirect'){ window.location.replace(response.logoutUrl); } else { this.get('flashMessages').success('general.confirmLogout'); window.location.replace(config.rootURL); } }); } }, beforeModel() { const i18n = this.get('i18n'); const moment = this.get('moment'); moment.setLocale(i18n.get('locale')); }, actions: { willTransition: function() { let controller = this.controllerFor('application'); controller.set('errors', []); controller.set('showErrorDisplay', false); } } });
var map = [ [0x1, 0x8], [0x2, 0x10], [0x4, 0x20], [0x40, 0x80] ] function Canvas(width, height) { if(width%2 != 0) { throw new Error('Width must be multiple of 2!'); } if(height%4 != 0) { throw new Error('Height must be multiple of 4!'); } this.width = width; this.height = height; this.content = new Buffer(width*height/8); this.content.fill(0); } var methods = { set: function(coord, mask) { this.content[coord] |= mask; }, unset: function(coord, mask) { this.content[coord] &= ~mask; }, toggle: function(coord, mask) { this.content[coord] ^= mask; } }; Object.keys(methods).forEach(function(method) { Canvas.prototype[method] = function(x, y) { if(!(x >= 0 && x < this.width && y >= 0 && y < this.height)) { return; } x = Math.floor(x); y = Math.floor(y); var nx = Math.floor(x/2); var ny = Math.floor(y/4); var coord = nx + this.width/2*ny; var mask = map[y%4][x%2]; methods[method].call(this, coord, mask); } }); Canvas.prototype.clear = function() { this.content.fill(0); }; Canvas.prototype.frame = function frame(delimiter) { delimiter = delimiter || '\n'; var result = []; for(var i = 0, j = 0; i < this.content.length; i++, j++) { if(j == this.width/2) { result.push(delimiter); j = 0; } if(this.content[i] == 0) { result.push(' '); } else { result.push(String.fromCharCode(0x2800 + this.content[i])) } } result.push(delimiter); return result.join(''); }; module.exports = Canvas;
/** * Test for fur bin. * Runs with mocha. */ 'use strict' const assert = require('assert') const fs = require('fs') const furBin = require.resolve('../bin/fur') const execcli = require('execcli') const mkdirp = require('mkdirp') let tmpDir = __dirname + '/../tmp' describe('bin', function () { this.timeout(24000) before(async () => { await mkdirp(tmpDir) }) after(async () => { }) it('Generate favicon', async () => { let filename = tmpDir + '/testing-bin-favicon.png' await execcli(furBin, [ 'favicon', filename ]) assert.ok(fs.existsSync(filename)) }) it('Generate banner', async () => { let filename = tmpDir + '/testing-bin-banner.png' await execcli(furBin, [ 'banner', filename ]) assert.ok(fs.existsSync(filename)) }) }) /* global describe, before, after, it */
Router.map(function(){ this.route('home',{ path:'/', template: 'home', onBeforeAction: function(pause){ this.subscribe('getAlgosByReg',Session.get('mainQuery')).wait(); this.subscribe('getAlgosByName',Session.get('mainQuery')).wait(); this.subscribe('getAlgosByKeyWord',Session.get('mainQuery')).wait(); } }); this.route('guide',{ path:'/guidelines', template:'guidelines' }); this.route('pediaHome',{ path: '/algos', template:'pedia', onBeforeAction: function(pause){ this.subscribe('getAllAlgos'); Session.set('pediaAiD',""); } }); this.route('pediaSpecific',{ path: '/algos/:_id', template:'pedia', onBeforeAction: function(pause){ this.subscribe('getAllAlgos'); this.subscribe('codeByAlgo',this.params._id); Session.set('pediaAiD',this.params._id); } }); this.route('langs',{ template: 'langList', onBeforeAction: function(pause){ Session.set('langPageLang',""); } }); this.route('langSearch',{ path: '/langs/:_id', template: 'langList', onBeforeAction: function(pause){ this.subscribe('codeByLang',this.params._id).wait(); Session.set('langPageLang',this.params._id); } }); this.route('users',{ path: '/users/:_id', template:'userPage', onBeforeAction: function(pause){ this.subscribe('getUserCode',this.params._id).wait(); this.subscribe('getUserAlgos',this.params._id).wait(); var uDoc = Meteor.users.findOne({_id:this.params._id}); Session.set('lastUserSearch',uDoc); if(Session.equals('lastUserSearch',undefined)){ pause(); } } }); this.route('pedia',{ path:'/pedia/:_id', template: 'entryPage', onBeforeAction: function(pause){ this.subscribe('algoParticular',this.params._id).wait(); var aDoc = AlgoPedia.findOne({AiD:this.params._id}); Session.set('lastAlgoSearch',aDoc); Session.set('lsiSelected',null); Session.set('tabSelect','first'); Session.set('lsiLangSearch',null); if(Session.equals('lastAlgoSearch',undefined)){ pause(); } } }); this.route('pediaSearch',{ path:'/pedia/:algo/:search', template: 'entryPage', onBeforeAction: function(pause){ this.subscribe('algoParticular',this.params.algo).wait(); var aDoc=AlgoPedia.findOne({AiD:this.params.algo}); Session.set('lastAlgoSearch',aDoc); if(this.params.search==="showAll"){ this.subscribe('codeByAlgo',this.params.algo).wait(); Session.set('lsiLangSearch',null); Session.set('lsiSelected',null); Session.set('tabSelect','second'); if(Session.equals('lastAlgoSearch',undefined)){ pause(); } } else{ this.subscribe('codeByAlgoAndLang',this.params.algo,this.params.search).wait(); var lDoc = Languages.findOne({Slug:this.params.search}); Session.set('lsiLangSearch',lDoc); Session.set('lsiSelected',null); Session.set('tabSelect','second'); if(Session.equals('lastAlgoSearch',undefined)){ pause(); } if(Session.equals('lsiLangSearch',undefined)){ pause(); } } } }); this.route('lsiSearchRoute',{ path:'/pedia/:algo/:lang/:search', template: 'entryPage', onBeforeAction: function(pause){ this.subscribe('getComments',this.params.search); this.subscribe('algoParticular',this.params.algo).wait(); var aDoc=AlgoPedia.findOne({AiD:this.params.algo}); Session.set('lastAlgoSearch',aDoc); if(this.params.lang==="showAll"){ this.subscribe('codeByAlgo',this.params.algo).wait(); Session.set('lsiSelected',this.params.search); Session.set('tabSelect','second'); Session.set('lsiLangSearch',null); if(Session.equals('lastAlgoSearch',undefined)){ pause(); } } else{ this.subscribe('codeByAlgoAndLang',this.params.algo,this.params.lang).wait(); var lDoc = Languages.findOne({Slug:this.params.lang}); Session.set('lsiSelected',this.params.search); Session.set('tabSelect','second'); Session.set('lsiLangSearch',lDoc); if(Session.equals('lastAlgoSearch',undefined)){ pause(); } if(Session.equals('lsiLangSearch',undefined)){ pause(); } } } }); }); Router.configure({ layoutTemplate: 'layout_main', });
/** * Imports */ var path = require('path'); var fs = require('fs'); var _ = require('lodash'); /** * BaseDbContext class * @param {Object} options */ var BaseDbContext = module.exports = function(options) { options || (options = {}); this.entities = {}; this._loadModels(); this.initialize.apply(this, arguments); } _.extend(BaseDbContext.prototype, { initialize: function () {}, modelsFolder: [], _loadModels: function () { if(!this.db) { return; } var self = this; this.modelsFolder.forEach(function (folderpath) { fs.readdirSync(folderpath).forEach(function(file) { var modelName = file.split('.')[0]; var model = self.db.import(path.join(folderpath, file)); self.entities[modelName] = model; }); Object.keys(self.entities).forEach(function(modelName) { if ('associate' in self.entities[modelName]) { self.entities[modelName].associate(self.entities); } }); }); }, sync: function () { return this.db.sync(); }, drop: function () { return this.db.drop(); } }); /** * JavaScript extend function */ function extend(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function() { return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); child.prototype = Object.create(parent.prototype, { constructor: { value: child, enumerable: false, writable: true, configurable: true } }); if (protoProps) _.extend(child.prototype, protoProps); child.__super__ = parent.prototype; return child; }; BaseDbContext.extend = extend; module.exports = BaseDbContext;
import React, {Component} from "react"; import { addAnimationId } from './modules/animationFunctions.js' import '../scss/dev-projects.css'; import close from "../assets/close.png"; export default class DevProjects extends Component { componentDidMount() { addAnimationId('dev-projects', 'dev-section-fadein') } render() { return ( <div id="dev-projects"> <i onClick={this.props.closeButtonClick} className="fal fa-times"></i> <div className="project-container"> <div> <p>PERSONAL SITE PROJECT</p> <p>BUILT A NEW PERSONAL SITE USING REACT.JS WHILE UTILIZING VARIOUS ANIMATIONS AND TRANSITIONS</p> </div> <div> <a href="https://github.com/Ayaz2589/personal_site" target="_blank"> VIEW PERSONAL SITE CODEBASE </a> </div> </div> </div> ); } };
import React, { PropTypes } from 'react'; import Spinner from './Spinner'; const ModalOverlay = (props) => { const isActive = props.active ? 'active' : ''; const spinner = props.spinner ? <Spinner /> : ''; return ( <div id="modal-overlay" className={isActive}> {spinner} </div> ); }; ModalOverlay.propTypes = { active: PropTypes.bool, spinner: PropTypes.bool, }; export default ModalOverlay;
version https://git-lfs.github.com/spec/v1 oid sha256:1371b661d4ebad753ee72a0b75d51aca5ca885cbb51d046e634951057b5314f6 size 144
function tabCtrl(id) { var element = document.querySelectorAll('[data-selector="tabbar/tab"]'); for (var i = 0; i < element.length; i++) { if (element[i].dataset.id === id) { element[i].classList.add('tabbar__tab__active'); } else { element[i].classList.remove('tabbar__tab__active'); } } } function tabItemCtrl(id) { var element = document.querySelectorAll('[data-selector="tabbar/item"]'); for (var i = 0; i < element.length; i++) { if (element[i].dataset.id === id) { element[i].classList.remove('tabbar__item--hidden'); } else { element[i].classList.add('tabbar__item--hidden'); } } } function init() { var links = document.querySelectorAll('[data-selector="tabbar/tab"]'); for (var i = 0; i < links.length; i++) { links[i].addEventListener('click', function (event) { event.preventDefault(); tabCtrl(this.dataset.id); tabItemCtrl(this.dataset.id); }, false); } } export default init;
import core from 'comindware/core'; import CanvasView from 'demoPage/views/CanvasView'; export default function() { const model = new Backbone.Model({ referenceValue: { id: 'test.1', text: 'Test Reference 1' } }); return new CanvasView({ view: new core.form.editors.ReferenceBubbleEditor({ model, key: 'referenceValue', autocommit: true, showEditButton: true, controller: new core.form.editors.reference.controllers.DemoReferenceEditorController() }), presentation: "{{#if referenceValue}}{ id: '{{referenceValue.id}}', text: '{{referenceValue.text}}' }{{else}}null{{/if}}" }); }
'use strict'; // Use local.env.js for environment variables that grunt will set when the server starts locally. // Use for your api keys, secrets, etc. This file should not be tracked by git. // // You will need to set these on the server you deploy to. module.exports = { DOMAIN: 'http://localhost:9000', SESSION_SECRET: 'zebratest-secret', // Control debug level for modules using visionmedia/debug DEBUG: '' };
import { template, traverse, types as t } from "@babel/core"; import { environmentVisitor } from "@babel/helper-replace-supers"; const findBareSupers = traverse.visitors.merge([ { Super(path) { const { node, parentPath } = path; if (parentPath.isCallExpression({ callee: node })) { this.push(parentPath); } }, }, environmentVisitor, ]); const referenceVisitor = { "TSTypeAnnotation|TypeAnnotation"(path) { path.skip(); }, ReferencedIdentifier(path) { if (this.scope.hasOwnBinding(path.node.name)) { this.scope.rename(path.node.name); path.skip(); } }, }; function handleClassTDZ(path, state) { if ( state.classBinding && state.classBinding === path.scope.getBinding(path.node.name) ) { const classNameTDZError = state.file.addHelper("classNameTDZError"); const throwNode = t.callExpression(classNameTDZError, [ t.stringLiteral(path.node.name), ]); path.replaceWith(t.sequenceExpression([throwNode, path.node])); path.skip(); } } const classFieldDefinitionEvaluationTDZVisitor = { ReferencedIdentifier: handleClassTDZ, }; export function injectInitialization(path, constructor, nodes, renamer) { if (!nodes.length) return; const isDerived = !!path.node.superClass; if (!constructor) { const newConstructor = t.classMethod( "constructor", t.identifier("constructor"), [], t.blockStatement([]), ); if (isDerived) { newConstructor.params = [t.restElement(t.identifier("args"))]; newConstructor.body.body.push(template.statement.ast`super(...args)`); } [constructor] = path.get("body").unshiftContainer("body", newConstructor); } if (renamer) { renamer(referenceVisitor, { scope: constructor.scope }); } if (isDerived) { const bareSupers = []; constructor.traverse(findBareSupers, bareSupers); let isFirst = true; for (const bareSuper of bareSupers) { if (isFirst) { bareSuper.insertAfter(nodes); isFirst = false; } else { bareSuper.insertAfter(nodes.map(n => t.cloneNode(n))); } } } else { constructor.get("body").unshiftContainer("body", nodes); } } export function extractComputedKeys(ref, path, computedPaths, file) { const declarations = []; const state = { classBinding: path.node.id && path.scope.getBinding(path.node.id.name), file, }; for (const computedPath of computedPaths) { const computedKey = computedPath.get("key"); if (computedKey.isReferencedIdentifier()) { handleClassTDZ(computedKey, state); } else { computedKey.traverse(classFieldDefinitionEvaluationTDZVisitor, state); } const computedNode = computedPath.node; // Make sure computed property names are only evaluated once (upon class definition) // and in the right order in combination with static properties if (!computedKey.isConstantExpression()) { const ident = path.scope.generateUidIdentifierBasedOnNode( computedNode.key, ); // Declaring in the same block scope // Ref: https://github.com/babel/babel/pull/10029/files#diff-fbbdd83e7a9c998721c1484529c2ce92 path.scope.push({ id: ident, kind: "let", }); declarations.push( t.expressionStatement( t.assignmentExpression("=", t.cloneNode(ident), computedNode.key), ), ); computedNode.key = t.cloneNode(ident); } } return declarations; }
import React from "react" import Presentation from "./Presentation" import Icon from 'material-ui/Icon' import IconButton from 'material-ui/IconButton' import Grid from 'material-ui/Grid' import Typography from 'material-ui/Typography' import { colors } from "../themes/coinium" require("../themes/coinium/index.css") const FOOTER_WIDTH = 60 const MODES = { PRESENTATION: 0, HELP: 1 } export default class App extends React.Component { constructor(props) { super(props); this.state = { mode: MODES.PRESENTATION }; } goToSlide(slideName) { this.setState({mode: MODES.PRESENTATION}, () => { location.hash = `/${slideName}` }) } renderHelp() { const style = { height: '100%', backgroundColor: colors.primary } const creditsStyle = { opacity: 0.8 } return ( <Grid container direction="column" justify="center" align="center" style={style}> <Typography type="caption" style={creditsStyle}> Copyright 2017 Coinium, Inc <hr /> Contact us: <a href="mailto:support@coinium.com">support@coinium.com</a> <hr /> {"Some icons based on the work of "} <a href="http://www.freepik.com" title="Freepik">Freepik</a> {" from "} <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> {" are licensed by "} <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a> </Typography> </Grid> ) } renderCurrentPage() { switch (this.state.mode) { case MODES.PRESENTATION: return <Presentation /> case MODES.HELP: return this.renderHelp() default: return ( <Typography>Please reload</Typography> ) } } render() { const mainStyle = { position: 'fixed', top: 0, right: FOOTER_WIDTH, bottom: 0, left: 0, boxShadow: '2px 0px 4px rgba(0,0,0,0.4)', zIndex: 2, overflow: 'hidden' } const navStyle = { background: colors.secondary, position: 'fixed', top: 0, right: 0, bottom: 0, left: 'auto', width: FOOTER_WIDTH, zIndex: 1 } const onHelpClick = () => { const mode = this.state.mode == MODES.HELP ? MODES.PRESENTATION : MODES.HELP this.setState({mode}) } return ( <Grid container className="App"> <Grid item style={mainStyle}> {this.renderCurrentPage()} </Grid> <Grid item container direction="column" justify="space-between" align="center" spacing={0} style={navStyle}> <Grid> <IconButton onClick={this.goToSlide.bind(this, "home")}> <Icon color="contrast">home</Icon> </IconButton> <IconButton onClick={this.goToSlide.bind(this, "problem")}> <Icon color="contrast">info_outline</Icon> </IconButton> <IconButton onClick={this.goToSlide.bind(this, "team")}> <Icon color="contrast">people</Icon> </IconButton> <IconButton onClick={this.goToSlide.bind(this, "mobile")}> <Icon color="contrast">phone_iphone</Icon> </IconButton> <IconButton onClick={this.goToSlide.bind(this, "signup")}> <Icon color="contrast">insert_drive_file</Icon> </IconButton> </Grid> <Grid> <IconButton onClick={onHelpClick}> <Icon color="contrast">help_outline</Icon> </IconButton> </Grid> </Grid> </Grid> ); } }
/** * 在球场 * zaiqiuchang.com */ const initialState = { users: {}, posts: {}, courts: {}, files: {}, userStats: {}, postStats: {}, courtStats: {}, fileStats: {} } export default (state = initialState, action) => { if (action.type === 'CACHE_OBJECTS') { let newState = Object.assign({}, state) for (let [k, v] of Object.entries(action)) { if (newState[k] === undefined) { continue } newState[k] = Object.assign({}, newState[k], v) } return newState } else if (action.type === 'RESET' || action.type === 'RESET_OBJECT_CACHE') { return initialState } else { return state } }
// ajax mode: abort // usage: $.ajax({ mode: "abort"[, port: "uniqueport"]}); // if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() var pendingRequests = {}, ajax; // Use a prefilter if available (1.5+) if ($.ajaxPrefilter) { $.ajaxPrefilter(function (settings, _, xhr) { var port = settings.port; if (settings.mode === "abort") { if (pendingRequests[port]) { pendingRequests[port].abort(); } pendingRequests[port] = xhr; } }); } else { // Proxy ajax ajax = $.ajax; $.ajax = function (settings) { var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode, port = ( "port" in settings ? settings : $.ajaxSettings ).port; if (mode === "abort") { if (pendingRequests[port]) { pendingRequests[port].abort(); } pendingRequests[port] = ajax.apply(this, arguments); return pendingRequests[port]; } return ajax.apply(this, arguments); }; }
export const FETCH_MESSAGES_REQUEST = 'FETCH_MESSAGES_REQUEST'; export const FETCH_MESSAGES_SUCCESS = 'FETCH_MESSAGES_SUCCESS'; export const FETCH_MESSAGES_ERROR = 'FETCH_MESSAGES_ERROR'; export const CREATE_MESSAGE_REQUEST = 'CREATE_MESSAGE_REQUEST'; export const CREATE_MESSAGE_SUCCESS = 'CREATE_MESSAGE_SUCCESS'; export const CREATE_MESSAGE_ERROR = 'CREATE_MESSAGE_ERROR'; export const UPDATE_MESSAGE_REQUEST = 'UPDATE_MESSAGE_REQUEST'; export const UPDATE_MESSAGE_SUCCESS = 'UPDATE_MESSAGE_SUCCESS'; export const UPDATE_MESSAGE_ERROR = 'UPDATE_MESSAGE_ERROR'; export const DELETE_MESSAGE_REQUEST = 'DELETE_MESSAGE_REQUEST'; export const DELETE_MESSAGE_SUCCESS = 'DELETE_MESSAGE_SUCCESS'; export const DELETE_MESSAGE_ERROR = 'DELETE_MESSAGE_ERROR';
var Model = require('./beer'); var Controller = { create: function(req, res) { var dados = req.body; var model = new Model(dados); model.save(function (err, data) { if (err){ console.log('Erro: ', err); res.json('Erro: ' + err); } else{ console.log('Cerveja Inserida: ', data); res.json(data); } }); }, retrieve: function(req, res) { var query = {}; Model.find(query, function (err, data) { if (err){ console.log('Erro: ', err); res.json('Erro: ' + err); } else{ console.log('Cervejas Listadas: ', data); res.json(data); } }); }, get: function(req, res) { var query = {_id: req.params.id}; Model.findOne(query, function (err, data) { if (err){ console.log('Erro: ', err); res.json('Erro: ' + err); } else{ console.log('Cervejas Listadas: ', data); res.json(data); } }); }, update: function(req, res) { var query = {_id: req.params.id}; var mod = req.body; Model.update(query, mod, function (err, data) { if (err){ console.log('Erro: ', err); res.json('Erro: ' + err); } else{ console.log('Cervejas alteradas: ', data); res.json(data); } }); }, delete: function(req, res) { var query = {_id: req.params.id}; // É multi: true CUIDADO! Model.remove(query, function(err, data) { if (err){ console.log('Erro: ', err); res.json('Erro: ' + err); } else{ console.log('Cervejas deletadas: ', data); res.json(data); } }); }, renderList: function(req, res) { var query = {}; Model.find(query, function (err, data) { if (err){ console.log('Erro: ', err); res.render('beers/error', { error: err }); } else{ console.log('Cervejas Listadas: ', data); res.render('beers/index', { title: 'Listagem das cervejas', beers: data }); } }); }, renderGet: function(req, res) { var query = {_id: req.params.id}; Model.findOne(query, function (err, data) { if (err){ console.log('Erro: ', err); res.render('beers/error', { error: err }); } else{ console.log('Cervejas consultada: ', data); res.render('beers/get', { title: 'Cerveja ' + data.name, beer: data }); } }); }, renderCreate: function(req, res) { res.render('beers/create', { title: 'Cadastro de Cerveja' }); }, renderUpdate: function(req, res) { var query = {_id: req.params.id}; Model.findOne(query, function (err, data) { if (err){ console.log('Erro: ', err); res.render('beers/error', { error: err }); } else{ console.log('Cervejas alteradas: ', data); res.render('beers/update', { title: 'Cerveja ' + data.name, beer: data }); } }); }, renderRemove: function(req, res) { var query = {_id: req.params.id}; Model.findOne(query, function (err, data) { if (err){ console.log('Erro: ', err); res.render('beers/error', { error: err }); } else{ console.log('Cervejas removidas: ', data); res.render('beers/remove', { title: 'Remover Cerveja ' + data.name, beer: data }); } }); } }; module.exports = Controller;
(function() { // numeral.js locale configuration // locale : Latvian (lv) // author : Lauris Bukšis-Haberkorns : https://github.com/Lafriks return { delimiters: { thousands: String.fromCharCode(160), decimal: ',' }, abbreviations: { thousand: ' tūkst.', million: ' milj.', billion: ' mljrd.', trillion: ' trilj.' }, ordinal: function(number) { return '.'; }, currency: { symbol: '€' } }; })();
module.exports = { out: "./docs/", readme: "README.md", name: "Persian Tools", includes: "./src", entryPoints: ["./src/index.ts"], exclude: ["**/test/**/*", "**/*.js", "**/dist/**/*", "**/src/dummy/**"], excludeExternals: true, includeVersion: true, excludePrivate: false, };
'use strict'; /** * Confirm new player name */ module.exports = (srcPath) => { const EventUtil = require(srcPath + 'EventUtil'); return { event: state => (socket, args) => { const say = EventUtil.genSay(socket); const write = EventUtil.genWrite(socket); write(`<bold>${args.name} doesn't exist, would you like to create it?</bold> <cyan>[y/n]</cyan> `); socket.once('data', confirmation => { say(''); confirmation = confirmation.toString().trim().toLowerCase(); if (!/[yn]/.test(confirmation)) { return socket.emit('player-name-check', socket, args); } if (confirmation === 'n') { say(`Let's try again...`); return socket.emit('create-player', socket, args); } return socket.emit('finish-player', socket, args); }); } }; };
import React, {Component} from 'react'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import {initialPlay, nextTrack, togglePlaying} from 'redux/modules/player'; import {starTrack, unstarTrack} from 'redux/modules/starred'; import {isTrackStarred} from 'utils/track'; const classNames = require('classnames'); const styles = require('./Player.scss'); @connect( state => ({player: state.player, starred: state.starred}), dispatch => bindActionCreators({initialPlay, nextTrack, starTrack, unstarTrack, togglePlaying}, dispatch)) export default class Player extends Component { constructor(props) { super(props); this.handleToggleClick = this.handleToggleClick.bind(this); this.handleNextTrack = this.handleNextTrack.bind(this); this.handleStarTrack = this.handleStarTrack.bind(this); this.handleStarTrackClick = this.handleStarTrackClick.bind(this); this.isStarred = this.isStarred.bind(this); this.isTrackSelected = this.isTrackSelected.bind(this); this.renderInfo = this.renderInfo.bind(this); } handleToggleClick() { const {initialPlay, player, togglePlaying} = this.props; // eslint-disable-line no-shadow const {currentTrack} = player; if (currentTrack) { togglePlaying(); } else { initialPlay(); } } handleNextTrack() { if (!this.isTrackSelected()) return; const {nextTrack} = this.props; // eslint-disable-line no-shadow nextTrack(); } handleStarTrack() { const {player, starTrack} = this.props; // eslint-disable-line no-shadow const {currentTrack} = player; starTrack(currentTrack); console.log('starrr'); } handleStarTrackClick() { if (this.isStarred()) { this.handleUnstarTrack(); } else { this.handleStarTrack(); } } handleUnstarTrack() { const {player, unstarTrack} = this.props; // eslint-disable-line no-shadow const {currentTrack} = player; unstarTrack(currentTrack); console.log('unstarrr'); } isStarred() { const {player, starred} = this.props; const {currentTrack} = player; if (!this.isTrackSelected()) return false; const {starredTracks} = starred; return isTrackStarred(currentTrack, starredTracks); } isTrackSelected() { const {player} = this.props; const {currentTrack} = player; return currentTrack ? true : false; } renderInfo() { const {player} = this.props; const {currentTrack} = player; if (!currentTrack) return ''; const { data: { title, artist: { name: artistName, url: artistUrl }, track: { url: trackUrl } } } = currentTrack; return ( <h3 className={styles['info__text']}> <a className={styles['info__text__title']} href={trackUrl} target="_blank">{title}</a> <span className={styles['info__text__divider']}></span> <a className={styles['info__text__artist']} href={artistUrl} target="_blank">{artistName}</a> </h3> ); } render() { const {player} = this.props; const { playing: isPlaying } = player; const isStarred = this.isStarred(); console.log('is starred?', isStarred); const trackIsSelected = this.isTrackSelected(); const rootClasses = classNames( styles['Player'], { [styles['state--empty']]: !trackIsSelected, [styles['state--playing']]: isPlaying, [styles['state--starred']]: isStarred, [styles['state--disabled']]: !trackIsSelected } ); return ( <div className={rootClasses}> <div className={styles['info']}> {this.renderInfo()} </div> <div className={styles['controls']}> <div className={[styles['btn'], styles['btn--star']].join(' ')} onClick={this.handleStarTrackClick}> <div className={styles['btnIcon']}></div> </div> <div className={[styles['btn'], styles['btn--share']].join(' ')}> <div className={styles['btnIcon']}></div> </div> <div className={[styles['btn'], styles['btn--toggle']].join(' ')} onClick={this.handleToggleClick}> <div className={styles['btnIcon']}></div> </div> <div className={[styles['btn'], styles['btn--skip']].join(' ')} onClick={this.handleNextTrack}> <div className={styles['btnIcon']}></div> </div> </div> </div> ); } } Player.propTypes = { initialPlay: React.PropTypes.func, nextTrack: React.PropTypes.func, player: React.PropTypes.object, starred: React.PropTypes.object, starTrack: React.PropTypes.func, unstarTrack: React.PropTypes.func, togglePlaying: React.PropTypes.func, };
import IntersectionObserverPolyfill from './resources/IntersectionObserverPolyfill'; import IntersectionObserverEntryPolyfill from './resources/IntersectionObserverEntryPolyfill'; export { IntersectionObserverEntryPolyfill, IntersectionObserverPolyfill, };
const path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const PATHS = { SRC: path.join(__dirname, 'src') }; const webpackConfig = { entry: ['./src/index.jsx'], plugins: [new ExtractTextPlugin('style.css')], devtool: 'source-map', node: { fs: 'empty' }, output: { path: __dirname, publicPath: '/', filename: 'bundle.js' }, module: { rules: [ { test: /\.(js|jsx)?$/, use: [ { loader: 'eslint-loader' } ], include: [PATHS.SRC], enforce: 'pre' }, { test: /\.jsx?$/, include: [path.resolve('src')], exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { cacheDirectory: true } } ] }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.(woff|eot|ttf|woff2)$/, use: { loader: 'url-loader' } }, { test: /\.(jpg|gif|png|svg)$/, use: { loader: 'file-loader?name=[name].[hash].[ext]' } } ] }, resolve: { extensions: ['.js', '.jsx'] }, devServer: { historyApiFallback: true, contentBase: './' } }; module.exports = webpackConfig;
import { curry, range, always } from 'ramda' const FALSE = always(false) export const makeGrid = curry((cell, size) => { const r = range(0, size) return r.map((y) => r.map((x) => cell(y, x))) }) export const makeBlankGrid = makeGrid(FALSE)
'use strict'; const resultsStorage = require('../lib/core/resultsStorage'); const moment = require('moment'); const expect = require('chai').expect; const timestamp = moment(); const timestampString = timestamp.format('YYYY-MM-DD-HH-mm-ss'); function createResultUrls(url, outputFolder, resultBaseURL) { return resultsStorage(url, timestamp, outputFolder, resultBaseURL).resultUrls; } describe('resultUrls', function() { describe('#hasBaseUrl', function() { it('should be false if base url is missing', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', undefined, undefined ); expect(resultUrls.hasBaseUrl()).to.be.false; }); it('should be true if base url is present', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', undefined, 'http://results.com' ); expect(resultUrls.hasBaseUrl()).to.be.true; }); }); describe('#reportSummaryUrl', function() { it('should create url with default output folder', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', undefined, 'http://results.com' ); expect(resultUrls.reportSummaryUrl()).to.equal( `http://results.com/www.foo.bar/${timestampString}` ); }); it('should create url with absolute output folder', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', '/root/leaf', 'http://results.com' ); expect(resultUrls.reportSummaryUrl()).to.equal('http://results.com/leaf'); }); it('should create url with relative output folder', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', '../leaf', 'http://results.com' ); expect(resultUrls.reportSummaryUrl()).to.equal('http://results.com/leaf'); }); }); describe('#absoluteSummaryPageUrl', function() { it('should create url with default output folder', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', undefined, 'http://results.com' ); expect( resultUrls.absoluteSummaryPageUrl('http://www.foo.bar/xyz') ).to.equal( `http://results.com/www.foo.bar/${ timestampString }/pages/www.foo.bar/xyz/` ); }); it('should create url with absolute output folder', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', '/root/leaf', 'http://results.com' ); expect( resultUrls.absoluteSummaryPageUrl('http://www.foo.bar/xyz') ).to.equal('http://results.com/leaf/pages/www.foo.bar/xyz/'); }); it('should create url with relative output folder', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', '../leaf', 'http://results.com' ); expect( resultUrls.absoluteSummaryPageUrl('http://www.foo.bar/xyz') ).to.equal('http://results.com/leaf/pages/www.foo.bar/xyz/'); }); }); describe('#relativeSummaryPageUrl', function() { it('should create url with default output folder', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', undefined, 'http://results.com' ); expect( resultUrls.relativeSummaryPageUrl('http://www.foo.bar/xyz') ).to.equal('pages/www.foo.bar/xyz/'); }); it('should create url with absolute output folder', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', '/root/leaf', 'http://results.com' ); expect( resultUrls.relativeSummaryPageUrl('http://www.foo.bar/xyz') ).to.equal('pages/www.foo.bar/xyz/'); }); it('should create url with relative output folder', function() { const resultUrls = createResultUrls( 'http://www.foo.bar', '../leaf', 'http://results.com' ); expect( resultUrls.relativeSummaryPageUrl('http://www.foo.bar/xyz') ).to.equal('pages/www.foo.bar/xyz/'); }); }); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery-ui //= require jquery_ujs //= require underscore-min //= require lumen/loader //= require lumen/bootswatch //= require bootstrap3-typeahead //= require bootstrap-datepicker //= require pages //= require airports //= require wishlists //= require base //= require reverse_geocoder // =require current_location //= require mapper //= require map_bounds //= require map
import test from 'ava'; import Nightmare from 'nightmare'; const nightmare = new Nightmare({ show: process.env.SHOW }); test('food', async t => { await nightmare .goto('http://localhost:3333'); const visible = await nightmare .click('#food') .wait(500) .visible('[class*=_box_]'); t.true(visible); const hidden = await nightmare .click('[class*=_buttonList_] li:last-child a') .wait(500) .visible('[class*=_box_]'); t.false(hidden); const completeFood = await nightmare .click('#food') .wait(1000) .click('[class*=_buttonList_] li:first-child a') .wait(1000) .click('[class*=_buttonList_] li:first-child a') // Meat .wait(1000) .click('[class*=_convenientList_] li:first-child a') // Beaf .click('[class*=_buttonList_] a') // Next .wait(1000) .click('[class*=_buttonList_] a') // I got it .wait(1000) .visible('[class*=_box_]'); t.false(completeFood); const completeFoodResult = await nightmare .evaluate(() => { return JSON.parse(document.getElementById('answer').innerText); }); t.is(completeFoodResult.type, 'Meat'); t.is(completeFoodResult.meat, 'beef'); const completeFoodUsingInput = await nightmare .click('#food') .wait(1000) .click('[class*=_buttonList_] li:first-child a') .wait(1000) .click('[class*=_buttonList_] li:first-child a') // Meat .wait(1000) .click('[class*=_convenientList_] li:last-child a') // Other .click('[class*=_buttonList_] a') // Next .wait(1000) .type('[class*=_convenientInput_]', 'foo') .click('[class*=_buttonList_] a') // Next .wait(1000) .click('[class*=_buttonList_] a') // I got it .wait(1000) .visible('[class*=_box_]'); t.false(completeFoodUsingInput); const completeFoodUsingInputResult = await nightmare .evaluate(() => { return JSON.parse(document.getElementById('answer').innerText); }); t.is(completeFoodUsingInputResult.type, 'Meat'); t.is(completeFoodUsingInputResult.meat, 'foo'); });
/** * Created by faspert on 28.04.2015. */ 'use strict'; angular.module('gardenApp') .directive('gvDygraph', function () { return { restrict: 'EAC', //E = element, A = attribute, C = class, M = comment scope: true , //use parent's scope //replace: 'true', // replace directive by template in html template: '<div id="graphdiv"></div>', link: function (scope, element, attrs) { //DOM manipulation console.log('testing the stuff'); var g = new Dygraph(element.children()[0], [[0,0]], { title: 'Temperature / Humidite', }); scope.$watch("data", function () { console.log('scope changes'); var options = scope.options; if (options === undefined) { options = {}; } //do not update if data is empty if (scope.data.length != 0) options.file = scope.data; console.log(scope.data) g.updateOptions(options); g.resetZoom(); g.resize(); }, true); } } });
'use strict'; //Setting up route angular.module('mean.system').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // For unmatched routes: $urlRouterProvider.otherwise('/'); // states for my app $stateProvider .state('home', { url: '/', templateUrl: 'public/system/views/index.html' }) .state('auth', { templateUrl: 'public/auth/views/index.html' }) .state('places', { url: '/places', templateUrl: 'public/system/views/places.html', reloadOnSearch: true, controller: 'PlacesController' }); } ]) .config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix('!'); } ]);
module.exports = { extends: ["standard", "standard-react"], env: { browser: true, es6: true }, globals: { graphql: true }, plugins: ["class-property"], parser: "babel-eslint", rules: { indent: ["off"], "no-unused-vars": [ "error", { varsIgnorePattern: "React" } ], "jsx-quotes": ["error", "prefer-double"], "react/prop-types": "off", "react/jsx-uses-react": "error", "react/jsx-uses-vars": "error", "react/react-in-jsx-scope": "error", "space-before-function-paren": "off" } };
Rc4Random = function(seed) { var keySchedule = []; var keySchedule_i = 0; var keySchedule_j = 0; function init(seed) { for (var i = 0; i < 256; i++) { keySchedule[i] = i; } var j = 0; for (var i = 0; i < 256; i++) { j = (j + keySchedule[i] + seed.charCodeAt(i % seed.length)) % 256; var t = keySchedule[i]; keySchedule[i] = keySchedule[j]; keySchedule[j] = t; } } init(seed); function getRandomByte() { keySchedule_i = (keySchedule_i + 1) % 256; keySchedule_j = (keySchedule_j + keySchedule[keySchedule_i]) % 256; var t = keySchedule[keySchedule_i]; keySchedule[keySchedule_i] = keySchedule[keySchedule_j]; keySchedule[keySchedule_j] = t; return keySchedule[(keySchedule[keySchedule_i] + keySchedule[keySchedule_j]) % 256]; } this.getRandomNumber = function() { var number = 0; var multiplier = 1; for (var i = 0; i < 8; i++) { number += getRandomByte() * multiplier; multiplier *= 256; } return number / 18446744073709551616; } }
const TelegramBot = require('node-telegram-bot-api'); const EnchancedTelegramTest = require('./EnhancedTelegramTest'); const { track, trackInline } = require('../src/analytics'); const { initHandlers } = require('../src/handlers'); function createBot() { return new TelegramBot('0123456789abcdef', { webhook: true }); } function createTestServer(callback) { const bot = createBot(); const analytics = { track: (msg, name) => track(msg, name, callback), trackInline: msg => trackInline(msg, callback) }; initHandlers(bot, analytics); return new EnchancedTelegramTest(bot); } module.exports = { createBot, createTestServer };
// Inject Bower components into source code // // grunt-wiredep: <https://github.com/stephenplusplus/grunt-wiredep> // wiredep: <https://github.com/taptapship/wiredep> 'use strict'; module.exports = { markups: {<% if (cfg.html) { %> src: ['<%%= path.markups %>/**/*.html']<% } %><% if (cfg.pug) { %> src: ['<%%= path.markups %>/**/*.{pug,jade}']<% } %><% if (cfg.modernizr) { %>, exclude: ['bower_components/modernizr/modernizr.js']<% } %>, // Force absolute URL // "../bower_components/xxxx" -> "/bower_components/xxxx" ignorePath: /(\.\.\/)*\.\.(?=\/)/<% if (cfg.pug) { %>, // Support "*.pug" files fileTypes: { pug: { block: /(([ \t]*)\/\/-?\s*bower:*(\S*))(\n|\r|.)*?(\/\/-?\s*endbower)/gi, detect: { js: /script\(.*src=['"]([^'"]+)/gi, css: /link\(.*href=['"]([^'"]+)/gi }, replace: { js: 'script(src=\'{{filePath}}\')', css: 'link(rel=\'stylesheet\', href=\'{{filePath}}\')' } } }<% } %> }<% if (cfg.sass || cfg.less || cfg.stylus) { %>, styles: {<% if (cfg.sass) { %> src: ['<%%= path.styles %>/**/*.{scss,sass}']<% } %><% if (cfg.less) { %> src: ['<%%= path.styles %>/**/*.less']<% } %><% if (cfg.stylus) { %> src: ['<%%= path.styles %>/**/*.styl']<% } %>, // Import from bower_components directory // "../bower_components/xxxx" -> "xxxx" ignorePath: /(\.\.\/)*bower_components\// }<% } %> };
/* eslint no-console: [0] */ 'use strict' const Email = require('trailpack-proxy-email').Email module.exports = class Customer extends Email { /** * * @param customer * @param data * @param options * @returns {Promise.<{type: string, subject: string, text: string, html:string, send_email:boolean}>} */ invite(customer, data, options) { const Customer = this.app.orm['Customer'] let resCustomer return Customer.resolve(customer, options) .then(_customer => { if (!_customer) { throw new Error('Customer did not resolve') } resCustomer = _customer const subject = data.subject || `${ resCustomer.name } Invitation` const sendEmail = typeof data.send_email !== 'undefined' ? data.send_email : true return this.compose('invite', subject, resCustomer, sendEmail) }) } /** * * @param customer * @param data * @param options * @returns {Promise.<{type: string, subject: string, text: string, html:string, send_email:boolean}>} */ inviteAccepted(customer, data, options) { const Customer = this.app.orm['Customer'] let resCustomer return Customer.resolve(customer, options) .then(_customer => { if (!_customer) { throw new Error('Customer did not resolve') } resCustomer = _customer const subject = data.subject || `${ resCustomer.name } Invite Accepted` const sendEmail = typeof data.send_email !== 'undefined' ? data.send_email : true return this.compose('inviteAccepted', subject, resCustomer, sendEmail) }) } /** * * @param customer * @param data * @param options * @returns {Promise.<{type: string, subject: string, text: string, html:string, send_email:boolean}>} */ accountBalanceUpdated(customer, data, options) { const Customer = this.app.orm['Customer'] let resCustomer return Customer.resolve(customer, options) .then(_customer => { if (!_customer) { throw new Error('Customer did not resolve') } resCustomer = _customer const subject = data.subject || `${ resCustomer.name } Account Balance Updated` const sendEmail = typeof data.send_email !== 'undefined' ? data.send_email : true return this.compose('accountBalanceUpdated', subject, resCustomer, sendEmail) }) } /** * * @param customer * @param data * @param options */ accountBalanceDeducted(customer, data, options) { const Customer = this.app.orm['Customer'] let resCustomer return Customer.resolve(customer, options) .then(_customer => { if (!_customer) { throw new Error('Customer did not resolve') } resCustomer = _customer const subject = data.subject || `${ resCustomer.name } Account Balance Deducted` const sendEmail = typeof data.send_email !== 'undefined' ? data.send_email : true return this.compose('accountBalanceDeducted', subject, resCustomer, sendEmail) }) } /** * * @param customer * @param data * @param options */ retarget(customer, data, options) { const Customer = this.app.orm['Customer'] let resCustomer return Customer.resolve(customer, options) .then(_customer => { if (!_customer) { throw new Error('Customer did not resolve') } resCustomer = _customer const subject = data.subject || `${ resCustomer.name } you have items in your cart!` const sendEmail = typeof data.send_email !== 'undefined' ? data.send_email : true return this.compose('retarget', subject, resCustomer, sendEmail) }) } }
/* eslint-disable global-require */ import React from 'react'; import { Router, Route, IndexRoute } from 'react-router'; import App from './modules/App/App'; import Landing from './modules/App/Landing'; import TalentInput from './modules/App/TalentInput'; import Performer from './modules/App/Performer'; // require.ensure polyfill for node if (typeof require.ensure !== 'function') { require.ensure = function requireModule(deps, callback) { callback(require); }; } /* Workaround for async react routes to work with react-hot-reloader till https://github.com/reactjs/react-router/issues/2182 and https://github.com/gaearon/react-hot-loader/issues/288 is fixed. */ if (process.env.NODE_ENV !== 'production') { // Require async routes only in development for react-hot-reloader to work. // require('./modules/Post/pages/PostListPage/PostListPage'); // require('./modules/Post/pages/PostDetailPage/PostDetailPage'); } // react-router setup with code-splitting // More info: http://blog.mxstbr.com/2016/01/react-apps-with-pages/ export default ( <Router> <Route path="/" component={Landing} /> {/*} <IndexRoute getComponent={(nextState, cb) => { require.ensure([], require => { cb(null, require('./modules/Post/pages/PostDetailPage/PostDetailPage').default); }); }} />*/} <Route path="/room" component={Performer} /> {/* <Route path="/index" getComponent={(nextState, cb) => { require.ensure([], require => { cb(null, require('./modules/Post/pages/PostDetailPage/PostDetailPage').default); }); }} />*/} {/*</Route>*/} <Route path="/talent" component={TalentInput} /> </Router> );
function solve(params) { var N = parseInt(params[0]), K = parseInt(params[1]), numbersAsString = params[2]; var numbers = numbersAsString.split(' ').map(Number); var result = []; for (var i = 0; i < N; i += 1) { if(i+K-1 === N) { break; } var min = 1000000000, max = -1000000000; for (var j = 0; j < K; j += 1) { if(numbers[i+j] > max) { max = numbers[j+i]; } if(numbers[i+j] < min) { min = numbers[j+i]; } } var sum = min + max; result.push(sum); } console.log(result.join(',')); //print answer } var test1 = ['4', '2', '1 3 1 8'], test2 = ['5', '3', '7 7 8 9 10']; console.log(solve(test1)); console.log(solve(test2));
/** * Created by dima on 06.12.16. */ import React from 'react'; import ViButton from './ViButton'; import './ViFileDownload.css' const ViFileDownloadButton = function ({ onClick, assetUri, type, loading }) { return ( <div className="ViFileDownload"> {onClick && <ViButton onClick={() => { onClick(type) }} label={`Export ${type}`}/>} {assetUri && <div className="ViFileDownload-assetDownloadButtonWr"> <a className="ViFileDownload-assetDownloadButton" href={assetUri}>Download {type}</a> </div>} {loading && <div className="ViFileDownload-assetDownloadButtonWr">Loading...</div>} </div> ) } export default ViFileDownloadButton;
/* * GET home page. */ exports.index = function(req, res){ res.render('index', { title: 'DSA' }); }; exports.game = function (req,res){ res.render('game',{title: req.params.id }) };
const fs = require('fs'); module.exports = (params) => () => { fs.writeFileSync(`${params.projectRoot}/License.md`, params.license); return 'licenseMd: ok'; };
function Improvement(options) { this.name = options.name; this.image = options.image; this.depth = options.depth || 0; this.parent = options.parent; this.children = options.children || []; this.siblings = options.siblings || []; this.toDisplay = options.toDisplay || []; this.toBuild = options.toBuild || []; this.cost = options.cost; this.materials = options.materials; this.buildEvent = 'event:'+options.buildEvent; } Improvement.prototype = { /* * The build function will build the improvement, adding it to the list of * improvements built in the GameState and removing the needed materials * from the character's inventory. */ build: function() { GameState.buildImprovement(this.code); var character = GameState.getCharacter(); character.adjustCurrency(-this.cost); $.each(this.materials, function(key, value) { character.removeItem({ item:key, count:value }); }); }, /* * An improvement is active when it has been built and none of its children * have been built. */ isActive: function() { if (!GameState.isImprovementBuilt(this.code)) { return false; } for (var i=0; i<this.children.length; i++) { if (GameState.isImprovementBuilt(this.children[i])) { return false; } } return true; }, /* * Function used to check to see if the improvement can be built regardless * of whether the character has the materials or not. If this improvement * has a parent location that hasn't been built then this improvement cannot * be built. If this improvement has any sibling improvements that have been * built then this improvement cannot be built. */ canBuild: function() { if (this.canDisplay() == false) { return false; } for (var i=0; i<this.siblings.length; i++) { if (GameState.isImprovementBuilt(this.siblings[i])) { return false; } } return Resolver.meetsRequirements(this.toBuild); }, /* * Function used to check to see if an improvement should be displayed in * the list of improvements. Improvements with parent improvements will not * be displayed until their parent improvements have been built. */ canDisplay: function() { if (this.parent && !GameState.isImprovementBuilt(this.parent)) { return false; } return Resolver.meetsRequirements(this.toDisplay); }, /* * Function used to check to see if the character has both the currency and * materials needed to build the improvement. */ hasMaterials: function() { var character = GameState.getCharacter(); if (character.getCurrency() < this.cost) { return false; } var result = true; $.each(this.materials, function(key, value) { if (character.getItemQuantity(key) < value) { result = false; } }); return result; }, /* Get the description of the improvement from the interface data. */ getDescription: function() { return Data.getInterface('improvement_'+this.getCode()); }, getBuildEvent: function() { return this.buildEvent; }, getCode: function() { return this.code; }, getCost: function() { return this.cost; }, getDepth: function() { return this.depth; }, getImage: function() { return this.image; }, getMaterials: function() { return this.materials; }, getName: function() { return this.name; }, };
(function($, UI) { "use strict"; var $win = $(window), $doc = $(document), scrollspies = [], checkScrollSpy = function() { for(var i=0; i < scrollspies.length; i++) { UI.support.requestAnimationFrame.apply(window, [scrollspies[i].check]); } }; UI.component('scrollspy', { defaults: { "cls" : "uk-scrollspy-inview", "initcls" : "uk-scrollspy-init-inview", "topoffset" : 0, "leftoffset" : 0, "repeat" : false, "delay" : 0 }, init: function() { var $this = this, idle, inviewstate, initinview, fn = function(){ var inview = UI.Utils.isInView($this.element, $this.options); if(inview && !inviewstate) { if(idle) clearTimeout(idle); if(!initinview) { $this.element.addClass($this.options.initcls); $this.offset = $this.element.offset(); initinview = true; $this.trigger("uk.scrollspy.init"); } idle = setTimeout(function(){ if(inview) { $this.element.addClass("uk-scrollspy-inview").addClass($this.options.cls).width(); } }, $this.options.delay); inviewstate = true; $this.trigger("uk.scrollspy.inview"); } if (!inview && inviewstate && $this.options.repeat) { $this.element.removeClass("uk-scrollspy-inview").removeClass($this.options.cls); inviewstate = false; $this.trigger("uk.scrollspy.outview"); } }; fn(); this.check = fn; scrollspies.push(this); } }); var scrollspynavs = [], checkScrollSpyNavs = function() { for(var i=0; i < scrollspynavs.length; i++) { UI.support.requestAnimationFrame.apply(window, [scrollspynavs[i].check]); } }; UI.component('scrollspynav', { defaults: { "cls" : 'uk-active', "closest" : false, "topoffset" : 0, "leftoffset" : 0, "smoothscroll" : false }, init: function() { var ids = [], links = this.find("a[href^='#']").each(function(){ ids.push($(this).attr("href")); }), targets = $(ids.join(",")); var $this = this, inviews, fn = function(){ inviews = []; for(var i=0 ; i < targets.length ; i++) { if(UI.Utils.isInView(targets.eq(i), $this.options)) { inviews.push(targets.eq(i)); } } if(inviews.length) { var scrollTop = $win.scrollTop(), target = (function(){ for(var i=0; i< inviews.length;i++){ if(inviews[i].offset().top >= scrollTop){ return inviews[i]; } } })(); if(!target) return; if($this.options.closest) { links.closest($this.options.closest).removeClass($this.options.cls).end().filter("a[href='#"+target.attr("id")+"']").closest($this.options.closest).addClass($this.options.cls); } else { links.removeClass($this.options.cls).filter("a[href='#"+target.attr("id")+"']").addClass($this.options.cls); } } }; if(this.options.smoothscroll && UI["smoothScroll"]) { links.each(function(){ UI.smoothScroll(this, $this.options.smoothscroll); }); } fn(); this.element.data("scrollspynav", this); this.check = fn; scrollspynavs.push(this); } }); var fnCheck = function(){ checkScrollSpy(); checkScrollSpyNavs(); }; // listen to scroll and resize $doc.on("uk-scroll", fnCheck); $win.on("resize orientationchange", UI.Utils.debounce(fnCheck, 50)); // init code $doc.on("uk-domready", function(e) { $("[data-uk-scrollspy]").each(function() { var element = $(this); if (!element.data("scrollspy")) { var obj = UI.scrollspy(element, UI.Utils.options(element.attr("data-uk-scrollspy"))); } }); $("[data-uk-scrollspy-nav]").each(function() { var element = $(this); if (!element.data("scrollspynav")) { var obj = UI.scrollspynav(element, UI.Utils.options(element.attr("data-uk-scrollspy-nav"))); } }); }); })(jQuery, jQuery.UIkit);
// @license // Redistribution and use in source and binary forms ... // Class for sending and receiving postMessages. // Based off the library by Daniel Park (http://metaweb.com, http://postmessage.freebaseapps.com) // // Dependencies: // * None // // Copyright 2014 Carnegie Mellon University. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ''AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those of the // authors and should not be interpreted as representing official policies, either expressed // or implied, of Carnegie Mellon University. // // Authors: // Paul Dille (pdille@andrew.cmu.edu) // "use strict"; (function(window) { // Send postMessages. window.pm = function(options) { pm.send(options); }; // Bind a handler to a postMessage response. window.pm.bind = function(type, fn) { pm.bind(type, fn); }; // Unbind postMessage handlers window.pm.unbind = function(type, fn) { pm.unbind(type, fn); }; var pm = { // The origin domain. _origin: null, // Internal storage (keep track of listeners, etc). data: function(key, value) { if (value === undefined) { return pm._data[key]; } pm._data[key] = value; return value; }, _data: {}, // Send postMessages. send: function(options) { if (!options) { console.warn("Need to specify at least 3 options (origin, target, type)."); return; } if (options.origin) { if (!pm._origin) { pm._origin = options.origin; } } else { console.warn("postMessage origin must be specified."); return; } var target = options.target; if (!target) { console.warn("postMessage target window required."); return; } if (!options.type) { console.warn("postMessage message type required."); return; } var msg = {data: options.data, type: options.type}; if ("postMessage" in target) { // Send the postMessage. try { target.postMessage(JSON.stringify(msg), options.origin); } catch (ex) { console.warn("postMessage failed with " + ex.name + ":", ex.message); } } else { console.warn("postMessage not supported"); } }, // Listen to incoming postMessages. bind: function(type, fn) { if (!pm.data("listening.postMessage")) { if (window.addEventListener) { window.addEventListener("message", pm._dispatch, false); } // Make sure we create only one receiving postMessage listener. pm.data("listening.postMessage", true); } // Keep track of listeners and their handlers. var listeners = pm.data("listeners.postMessage"); if (!listeners) { listeners = {}; pm.data("listeners.postMessage", listeners); } var fns = listeners[type]; if (!fns) { fns = []; listeners[type] = fns; } fns.push({fn: fn, origin: pm._origin}); }, // Unbind postMessage listeners. unbind: function(type, fn) { var listeners = pm.data("listeners.postMessage"); if (listeners) { if (type) { if (fn) { // Remove specific listener var fns = listeners[type]; if (fns) { var newListeners = []; for (var i = 0, len = fns.length; i < len; i++) { var obj = fns[i]; if (obj.fn !== fn) { newListeners.push(obj); } } listeners[type] = newListeners; } } else { // Remove all listeners by type delete listeners[type]; } } else { // Unbind all listeners of all types for (var i in listeners) { delete listeners[i]; } } } }, // Run the handler, if one exists, based on the type defined in the postMessage. _dispatch: function(e) { var msg = {}; try { msg = JSON.parse(e.data); } catch (ex) { console.warn("postMessage data parsing failed: ", ex); return; } if (!msg.type) { console.warn("postMessage message type required."); return; } var listeners = pm.data("listeners.postMessage") || {}; var fns = listeners[msg.type] || []; for (var i = 0, len = fns.length; i < len; i++) { var obj = fns[i]; if (obj.origin && obj.origin !== '*' && e.origin !== obj.origin) { console.warn("postMessage message origin mismatch: ", e.origin, obj.origin); continue; } // Run handler try { obj.fn(msg.data); } catch (ex) { throw ex; } } } }; })(this);
require.config({ urlArgs: "v=" + (new Date()).getTime() }); require(["game"], function(game) { // I know it's ugly but it works, make game a global object G = game; G.init(); $(window).resize(G.camera.resize); G.render(); });
define([], function () { var TAGNAMES = { 'select':'input', 'change':'input', 'submit':'form', 'reset':'form', 'error':'img', 'load':'img', 'abort':'img' }; var Utility = function() { }; Utility.isEventSupported = function(eventName) { var el = document.createElement(TAGNAMES[eventName] || 'div'); eventName = 'on' + eventName; var isSupported = (eventName in el); if (!isSupported) { el.setAttribute(eventName, 'return;'); isSupported = typeof el[eventName] == 'function'; } el = null; return isSupported; }; Utility.getSupportedEvent = function(events) { // get the length var len = events.length; if (typeof(len) == 'undefined') { len = 0; } for (var i = 0; i < len; i++) { if (Utility.isEventSupported(events[i])) { return events[i]; } } return null; }; return Utility; });
var exec = require('child_process').exec; exports.setHostname = function(envSettings){ var command = 'hostname'; exec(command,[], function (error, stdout, stderr) { if(error){ console.log('error when executing: ' + command); console.log('output : ' + stderr); } console.log('hostname : ' + stdout); var result = stdout.replace(/(\r\n|\n|\r)/gm,""); envSettings.serverPath = result; }); };
//AppliedRules.defineSetByView module.exports = (function( viewId ){ return this.defineSetByTag( viewId ); });
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS201: Simplify complex destructure assignments * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const { CompositeDisposable } = require('atom') let MinimapBookmarksBinding module.exports = { isActive () { return this.active }, activate () { this.active = false this.subscriptions = new CompositeDisposable() this.bindings = new Map() require('atom-package-deps').install('minimap-git-diff') }, consumeMinimapServiceV1 (minimap) { this.minimap = minimap this.minimap.registerPlugin('bookmarks', this) }, deactivate () { if (this.minimap) { this.minimap.unregisterPlugin('bookmarks') } this.minimap = null }, activatePlugin () { if (this.active) { return } const bookmarksPkg = atom.packages.getLoadedPackage('bookmarks') if (!bookmarksPkg) { return } const bookmarks = bookmarksPkg.mainModule this.active = true this.minimapsSubscription = this.minimap.observeMinimaps(minimap => { if (!MinimapBookmarksBinding) { MinimapBookmarksBinding = require('./minimap-bookmarks-binding') } const binding = new MinimapBookmarksBinding(minimap, bookmarks) this.bindings.set(minimap.id, binding) const subscription = minimap.onDidDestroy(() => { binding.destroy() this.subscriptions.remove(subscription) subscription.dispose() this.bindings.delete(minimap.id) }) this.subscriptions.add(subscription) }) }, deactivatePlugin () { if (!this.active) { return } const bindings = this.bindings.values() for (const binding of bindings) { binding.destroy() } this.bindings.clear() this.active = false this.minimapsSubscription.dispose() this.subscriptions.dispose() }, }
/* global ga */ import 'core-js/fn/array/find-index' import 'core-js/fn/string/starts-with' import './index.css' import '../node_modules/md-components/style.css' import React from 'react' import ReactDOM from 'react-dom' import {Route, NavLink, HashRouter} from 'react-router-dom' import {Shell} from 'md-components' import BottomNavigationRoute from './bottomnavigationRoute' import ButtonRoute from './buttonRoute' import CardRoute from './cardRoute' import CheckboxRoute from './checkboxRoute' import ChipRoute from './chipRoute' import ExpansionPanelRoute from './expansionpanelRoute' import HeaderRoute from './headerRoute' import HomeRoute from './homeRoute' import IconRoute from './iconRoute' import ListRoute from './listRoute' import MenuRoute from './menuRoute' import ModalRoute from './modalRoute' import NavigationRoute from './navigationRoute' import ProgressRoute from './progressRoute' import RadiobuttonRoute from './radiobuttonRoute' import SelectRoute from './selectRoute' import SelectNativeRoute from './selectnativeRoute' import SliderRoute from './sliderRoute' import SnackbarRoute from './snackbarRoute' // import StepperRoute from './stepperRoute' import SwitchRoute from './switchRoute' import TableRoute from './tableRoute' import TabsRoute from './tabsRoute' import TabsControlledRoute from './tabscontrolledRoute' import TextfieldRoute from './textfieldRoute' import TextareaRoute from './textareaRoute' // import TooltipRoute from './tooltipRoute' class App extends React.Component { state = { title: 'HBM/md-components', subtitle: '' } onLinkChange = event => { const link = event.currentTarget // use google analytics to track single page apps // https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications if (window.ga) { ga('set', 'page', link.href) ga('send', 'pageview') } this.setState({ title: 'md-components', subtitle: link.text }) } componentDidMount () { this.setState({ subtitle: document.querySelector('a.active').text }) } render () { const links = [ <NavLink to='/' exact>Home</NavLink>, <NavLink to='/bottomnavigation'>Bottom Navigation</NavLink>, <NavLink to='/button'>Button</NavLink>, <NavLink to='/card'>Card</NavLink>, <NavLink to='/checkbox'>Checkbox</NavLink>, <NavLink to='/chip'>Chip</NavLink>, <NavLink to='/expansionpanel'>Expansion Panel</NavLink>, <NavLink to='/header'>Header</NavLink>, <NavLink to='/icon'>Icon</NavLink>, <NavLink to='/list'>List</NavLink>, <NavLink to='/menu'>Menu</NavLink>, <NavLink to='/modal'>Modal</NavLink>, <NavLink to='/navigation'>Navigation</NavLink>, <NavLink to='/progress'>Progress</NavLink>, <NavLink to='/radiobutton'>Radiobutton</NavLink>, <NavLink to='/select'>Select</NavLink>, <NavLink to='/selectnative'>Select Native</NavLink>, <NavLink to='/slider'>Slider</NavLink>, <NavLink to='/snackbar'>Snackbar</NavLink>, <NavLink to='/switch'>Switch</NavLink>, <NavLink to='/table'>Table</NavLink>, <NavLink to='/tabs'>Tabs</NavLink>, <NavLink to='/tabscontrolled'>TabsControlled</NavLink>, <NavLink to='/textfield'>Textfield</NavLink>, <NavLink to='/textarea'>Textarea</NavLink> ].map(link => React.cloneElement(link, {onClick: this.onLinkChange})) return ( <HashRouter> <Shell links={links} title={this.state.title} subtitle={this.state.subtitle} > <Route exact path='/' component={HomeRoute} /> <Route path='/bottomnavigation' component={BottomNavigationRoute} /> <Route path='/button' component={ButtonRoute} /> <Route path='/card' component={CardRoute} /> <Route path='/checkbox' component={CheckboxRoute} /> <Route path='/chip' component={ChipRoute} /> <Route path='/expansionpanel' component={ExpansionPanelRoute} /> <Route path='/header' component={HeaderRoute} /> <Route path='/icon' component={IconRoute} /> <Route path='/list' component={ListRoute} /> <Route path='/menu' component={MenuRoute} /> <Route path='/modal' component={ModalRoute} /> <Route path='/navigation' component={NavigationRoute} /> <Route path='/progress' component={ProgressRoute} /> <Route path='/radiobutton' component={RadiobuttonRoute} /> <Route path='/select' component={SelectRoute} /> <Route path='/selectnative' component={SelectNativeRoute} /> <Route path='/slider' component={SliderRoute} /> <Route path='/snackbar' component={SnackbarRoute} /> <Route path='/switch' component={SwitchRoute} /> <Route path='/table' component={TableRoute} /> <Route path='/tabs' component={TabsRoute} /> <Route path='/tabscontrolled' component={TabsControlledRoute} /> <Route path='/textfield' component={TextfieldRoute} /> <Route path='/textarea' component={TextareaRoute} /> </Shell> </HashRouter> ) } } ReactDOM.render(<App />, document.getElementById('root'))
import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import { lodash } from 'meteor/stevezhu:lodash'; import { Bert } from 'meteor/themeteorchef:bert'; import { moment } from 'meteor/momentjs:moment'; import 'meteor/sacha:spin'; import { Workshops } from '../../../api/workshops/schema.js'; import { UserQuestions } from '../../../api/userQuestions/schema.js'; import './myDay.jade'; import '../../components/connect/connect.js'; Template.myDay.onCreated(function() { this.autorun(() => { this.subscribe('allWorkshopsForTheDay'); this.subscribe('resultForQuestionsAnswered', Meteor.userId()); }); }); Template.myDay.helpers({ workshopData() { return Workshops.findOne({ _id: this._id }, { fields: { name: 1, dateStart: 1, dateEnd: 1, color: 1, peopleToGo: 1, description: 1 } }); }, workshopColor(index) { if (index % 2 === 0) { return 'grey2'; } else { return false; } }, customWorkshops() { let questions = UserQuestions.find({ userId: Meteor.userId(), answered: true, deprecated: false }, { fields: { result: 1 } }).fetch(); let questionsObject = {}; let questionsArray = []; questions.map((cur) => { cur.result.map((cur1) => { if (cur1.workshopId) { if (questionsObject[cur1.workshopId]) { questionsObject[cur1.workshopId].value += cur1.result; questionsObject[cur1.workshopId].long += 1; } else { questionsObject[cur1.workshopId] = { value: cur1.result, long: 1 }; } } }); }); for (var prop in questionsObject) { questionsArray.push({ _id: prop, value: lodash.round(questionsObject[prop].value / questionsObject[prop].long * 100, 2) }); } questionsArray.sort((a, b) => { if (a.value < b.value) { return 1; } else if (a.value > b.value) { return -1; } else { return 0; } }); return questionsArray; }, dateStart() { return moment(this.dateStart).format('H:mm'); }, dateEnd() { return moment(this.dateEnd).format('H:mm'); }, isUserAlreadyIn() { if (lodash.findIndex(this.peopleToGo, ['userId', Meteor.userId()]) !== -1) { return true; } else { return false; } } }); Template.myDay.events({ 'click .goToWorkshop': function(event) { event.preventDefault(); const data = { userId: Meteor.userId(), workshopId: this._id }; Meteor.call('addUserToWorkshop', data, (error) => { if (error) { return Bert.alert(error.message, 'danger', 'growl-top-right'); } }); }, 'click .removeFromWorkshop': function(event) { event.preventDefault(); const data = { userId: Meteor.userId(), workshopId: this._id }; Meteor.call('removeUserFromWorkshop', data, (error) => { if (error) { return Bert.alert(error.message, 'danger', 'growl-top-right'); } }); } });