text
stringlengths
2
6.14k
version https://git-lfs.github.com/spec/v1 oid sha256:59e6f2fa6c70c504d839d897c45f9a84348faf82342a31fb5818b1deb13861fa size 294301
exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('coffee').del() .then(function () { // Inserts seed entries return knex('coffee').insert([ { id: 1, name: 'Three Africas', producer_id: 1, flavor_profile: 'Fruity, radiant, creamy', varieties: 'Heirloom', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 2, name: 'Ethiopia Bulga', producer_id: 2, flavor_profile: 'Cotton Candy, Strawberry, Sugar, Tangerine', varieties: 'Heirloom', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 3, name: 'Columbia Andino', producer_id: 2, flavor_profile: 'Butterscotch Citrus', varieties: 'Bourbon, Caturra, Typica', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 4, name: 'Colombia Popayán Fall Harvest', producer_id: 1, flavor_profile: 'Baking spice, red apple, nougat', varieties: '', description: 'Lorem ipsum', created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }]) .then(() => { return knex.raw("SELECT setval('coffee_id_seq', (SELECT MAX(id) FROM coffee));"); }); }); };
'use strict'; var express = require('express'), router = express.Router(), Post = require('../models/post'); module.exports = function (app) { app.use('/', router); }; router.get('/', function (req, res, next) { var posts = [new Post({ "title": "dummy posty" }), new Post()]; res.render('index', { title: 'Brian Mitchell', active: {active_home: true}, posts: posts }); });
"use strict"; const express = require('express'); const router = express.Router(); const quoteCtrl = require('../controllers/quote.js'); //returns an array of stocks that potentially match the query string //no result will return an empty string router.get('/quote/:quote', quoteCtrl.quote); module.exports = router;
var Blasticator = function() { var init = function() { registerSettings(); }; var showDialogue = function() { new ModalDialogue({ message:'This will destroy EVERYTHING. FOREVER.', buttons:[{ label:'Keep my data', role:'secondary', autoClose:true },{ label:'BURN IT ALL', role:'primary', autoClose:true, callback:function() { App.persister.clear(); window.location.reload(true); } }] }); }; var registerSettings = function() { App.settings.register([{ section:'Data', label:'Clear data', type:'button', iconClass:'fa-trash', callback:showDialogue }]); }; init(); };
(function () { window.AgidoMockups = window.AgidoMockups || {}; AgidoMockups.icons = AgidoMockups.icons || {}; AgidoMockups.icons.underline = new Kinetic.Group({name: "underlineIcon", width: 18, height: 20}); AgidoMockups.icons.underline.add(new Kinetic.Text({text: "U", fill: '#000', fontSize: 20, fontStyle: 'normal'})); AgidoMockups.icons.underline.add(new Kinetic.Line({ points: [1, 19, 13, 19], stroke: '#000', strokeWidth: 1 })); })();
(function() { var myPromise = new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition((pos) => { resolve(pos); }) }); function parsePosition(pos) { return { lat: pos.coords.latitude, lon: pos.coords.longitude } } function displayMap(pos) { let img = document.getElementById('theImg'); img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + pos.lat + "," + pos.lon + "&zoom=13&size=500x500&sensor=false"; } myPromise .then(parsePosition) .then(console.log) }());
module.exports = function(grunt) { grunt.initConfig({ // package.json is shared by all examples pkg: grunt.file.readJSON('../../package.json'), // Uglify the file at `src/foo.js` and output the result to `dist/foo.min.js` // // It's likely that this task is preceded by a `grunt-contrib-concat` task // to create a single file which is then uglified. uglify: { options: {}, dist: { files: { 'dist/foo.min.js': 'src/foo.js' // destination: source } } } }); // Load libraries used grunt.loadNpmTasks('grunt-contrib-uglify'); // Define tasks grunt.registerTask('default', ['uglify']); };
'use strict'; angular.module('adsApp').controller('AdminTownsController', ['$scope', '$rootScope', 'catalog', 'config', 'notify', function ($scope, $rootScope, catalog, config, notify) { $rootScope.pageTitle = 'Towns'; var usersConfig = config.users; var townsParams = { startPage: usersConfig.startPage, pageSize: usersConfig.pageSize }; $scope.getTowns = function () { $rootScope.loading = true; catalog.get('admin/towns', townsParams).then(function (towns) { $scope.towns = towns; }, function (error) { notify.message('Users filed to load!', error); }).finally(function () { $rootScope.loading = false; }); }; $scope.getTowns(); } ]);
/*! * Vitality v2.0.0 (http://themes.startbootstrap.com/vitality-v2.0.0) * Copyright 2013-2017 Start Bootstrap * Purchase a license to use this theme at (https://wrapbootstrap.com) */ /*! * Vitality v2.0.0 (http://themes.startbootstrap.com/vitality-v2.0.0) * Copyright 2013-2017 Start Bootstrap * Purchase a license to use this theme at (https://wrapbootstrap.com) */ // Load WOW.js on non-touch devices var isPhoneDevice = "ontouchstart" in document.documentElement; $(document).ready(function() { if (isPhoneDevice) { //mobile } else { //desktop // Initialize WOW.js wow = new WOW({ offset: 50 }) wow.init(); } }); (function($) { "use strict"; // Start of use strict // Collapse the navbar when page is scrolled $(window).scroll(function() { if ($("#mainNav").offset().top > 100) { $("#mainNav").addClass("navbar-shrink"); } else { $("#mainNav").removeClass("navbar-shrink"); } }); // Activate scrollspy to add active class to navbar items on scroll $('body').scrollspy({ target: '#mainNav', offset: 68 }); // Smooth Scrolling: Smooth scrolls to an ID on the current page // To use this feature, add a link on your page that links to an ID, and add the .page-scroll class to the link itself. See the docs for more details. $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: ($($anchor.attr('href')).offset().top - 68) }, 1250, 'easeInOutExpo'); event.preventDefault(); }); // Closes responsive menu when a link is clicked $('.navbar-collapse>ul>li>a, .navbar-brand').click(function() { $('.navbar-collapse').collapse('hide'); }); // Activates floating label headings for the contact form $("body").on("input propertychange", ".floating-label-form-group", function(e) { $(this).toggleClass("floating-label-form-group-with-value", !!$(e.target).val()); }).on("focus", ".floating-label-form-group", function() { $(this).addClass("floating-label-form-group-with-focus"); }).on("blur", ".floating-label-form-group", function() { $(this).removeClass("floating-label-form-group-with-focus"); }); // Owl Carousel Settings $(".team-carousel").owlCarousel({ items: 3, navigation: true, pagination: false, navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], }); $(".portfolio-carousel").owlCarousel({ singleItem: true, navigation: true, pagination: false, navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], autoHeight: true, mouseDrag: false, touchDrag: false, transitionStyle: "fadeUp" }); $(".testimonials-carousel, .mockup-carousel").owlCarousel({ singleItem: true, navigation: true, pagination: true, autoHeight: true, navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], transitionStyle: "backSlide" }); $(".portfolio-gallery").owlCarousel({ items: 3, }); // Magnific Popup jQuery Lightbox Gallery Settings $('.gallery-link').magnificPopup({ type: 'image', gallery: { enabled: true }, image: { titleSrc: 'title' } }); // Magnific Popup Settings $('.mix').magnificPopup({ type: 'image', image: { titleSrc: 'title' } }); // Vide - Video Background Settings $('header.video').vide({ mp4: "mp4/camera.mp4", poster: "img/agency/backgrounds/bg-mobile-fallback.jpg" }, { posterType: 'jpg' }); })(jQuery); // End of use strict
import pagination from '@admin/store/modules/paginationStore' import {HTTP} from '@shared/config/api' const state = { clientList: [] } const getters = { getClientList: state => state.clientList } const mutations = { set(state, {type, value}) { state[type] = value }, delete(state, {id}) { state.clientList = state.clientList.filter(w => w.Id !== id) }, deleteMultiple(state, {ids}) { state.clientList = state.clientList.filter(w => ids.indexOf(w.Id) === -1) }, update(state, {client}) { let index = state.clientList.findIndex(w => w.Id === client.Id) if (index !== -1) { state.clientList[index].Title = client.Title state.clientList[index].Email = client.Email state.clientList[index].Phone = client.Phone state.clientList[index].Note = client.Note } } } const actions = { getClients({commit, dispatch, getters}) { HTTP.get('api/Client', {params: getters.getParams}) .then((response) => { commit('set', { type: 'clientList', value: response.data.Items }) dispatch('setTotalItems', response.data.Total) }) .catch((error) => { window.console.error(error) }) }, createClient({dispatch}, client) { HTTP.post('api/Client', client) .then(() => { dispatch('getClients') }) .catch((error) => { window.console.error(error) }) }, updateClient({commit}, client) { HTTP.patch('api/Client', client) .then(() => { commit('update', {client: client}) }) .catch((error) => { window.console.error(error) }) }, deleteClient({commit, dispatch}, client) { HTTP.delete('api/Client', client) .then(() => { commit('delete', {id: client.params.id}) dispatch('addToTotalItems', -1) }) .catch((error) => { window.console.error(error) }) }, deleteMultipleClient({commit, dispatch}, clients) { HTTP.delete('api/Client', clients) .then(() => { commit('deleteMultiple', {ids: clients.params.ids}) dispatch('addToTotalItems', -clients.params.ids.length) }) .catch((error) => { window.console.error(error) }) } } export default { namespaced: true, state, mutations, actions, getters, modules: { Pagination: pagination() } }
import "cutaway" import { assert, report } from "tapeless" import createPlayer from "./main.js" const { ok, notOk, equal } = assert try { createPlayer() } catch (e) { ok .describe("will throw sans video input") .test(e, e.message) } const source = document.createElement("video") source.src = "" const { play, stop } = createPlayer(source) equal .describe("play") .test(typeof play, "function") notOk .describe("playing") .test(play()) equal .describe("stop") .test(typeof stop, "function") ok .describe("paused", "will operate") .test(stop()) report()
class dximagetransform_microsoft_maskfilter { constructor() { // Variant Color () {get} {set} this.Color = undefined; } } module.exports = dximagetransform_microsoft_maskfilter;
/** * Calculates the radius of the Hill Sphere, * for a body with mass `m1` * @param {Number} m1 Mass of the lighter body * @param {Number} m2 Mass of the heavier body * @param {Number} a Semi-major axis * @param {Number} e Eccentricity * @return {Number} Hill Sphere radius */ function hillSphere( m1, m2, a, e ) { return a * ( 1 - e ) * Math.pow( ( m1 / ( 3 * m2 ) ), 1/3 ) } module.exports = hillSphere
var httpRequester = (function() { var makeHttpRequest = function(url, type, data) { var deferred = $.Deferred(); $.ajax({ url: url, type: type, contentType: 'application/json', data: data, success: function(resultData) { deferred.resolve(resultData); }, error: function(error) { deferred.reject(error); } }); return deferred; }; var sendRequest = function(url, type, data) { return makeHttpRequest(url, type, data); }; return { sendRequest: sendRequest }; }());
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosCopy extends React.Component { render() { if(this.props.bare) { return <g> <g> <polygon points="144,416 144,400 144,112 112,112 112,448 352,448 352,416 160,416 "></polygon> <g> <path d="M325.3,64H160v48v288h192h48V139L325.3,64z M368,176h-80V96h16v64h64V176z"></path> </g> </g> </g>; } return <IconBase> <g> <polygon points="144,416 144,400 144,112 112,112 112,448 352,448 352,416 160,416 "></polygon> <g> <path d="M325.3,64H160v48v288h192h48V139L325.3,64z M368,176h-80V96h16v64h64V176z"></path> </g> </g> </IconBase>; } };IosCopy.defaultProps = {bare: false}
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Link } from 'react-router-dom'; import _ from 'lodash'; import User from './User'; import Loading from '../../components/Icon/Loading'; import './InterestingPeople.less'; import steemAPI from '../../steemAPI'; class InterestingPeopleWithAPI extends Component { static propTypes = { authenticatedUser: PropTypes.shape({ name: PropTypes.string, }), followingList: PropTypes.arrayOf(PropTypes.string), }; static defaultProps = { authenticatedUser: { name: '', }, followingList: [], }; state = { users: [], loading: true, noUsers: false, }; componentWillMount() { const authenticatedUsername = this.props.authenticatedUser.name; const usernameValidator = window.location.pathname.match(/@(.*)/); const username = usernameValidator ? usernameValidator[1] : authenticatedUsername; this.getBlogAuthors(username); } getBlogAuthors = (username = '') => steemAPI .getBlogAuthorsAsync(username) .then((result) => { const followers = this.props.followingList; const users = _.sortBy(result, user => user[1]) .reverse() .filter(user => !followers.includes(user[0])) .slice(0, 5) .map(user => ({ name: user[0] })); if (users.length > 0) { this.setState({ users, loading: false, noUsers: false, }); } else { this.setState({ noUsers: true, }); } }) .catch(() => { this.setState({ noUsers: true, }); }); render() { const { users, loading, noUsers } = this.state; if (noUsers) { return <div />; } if (loading) { return <Loading />; } return ( <div className="InterestingPeople"> <div className="InterestingPeople__container"> <h4 className="InterestingPeople__title"> <i className="iconfont icon-group InterestingPeople__icon" /> {' '} <FormattedMessage id="interesting_people" defaultMessage="Interesting People" /> </h4> <div className="InterestingPeople__divider" /> {users && users.map(user => <User key={user.name} user={user} />)} <h4 className="InterestingPeople__more"> <Link to={'/latest-comments'}> <FormattedMessage id="discover_more_people" defaultMessage="Discover More People" /> </Link> </h4> </div> </div> ); } } export default InterestingPeopleWithAPI;
var pagerun = require('pagerun'); // set for debug // pagerun.modulesRoot = '../'; pagerun.mode = 'test'; // pagerun.loadNpmPlugin('httpresponse'); pagerun.loadNpmPlugin('httpsummary'); pagerun.loadNpmPlugin('httperror'); pagerun.loadNpmPlugin('htmlhint'); pagerun.loadNpmPlugin('jserror'); pagerun.loadNpmPlugin('pagesummary'); pagerun.loadNpmPlugin('jsunit'); // pagerun.loadNpmPlugin('jscoverage'); process.on('message', function(config) { pagerun.setConfig(config); pagerun.run(function(result){ process.send(result); process.exit(0); }); });
'use strict'; $(function() { $.material.init(); $('#libraries').btsListFilter('#searcher', { itemChild: 'h3', resetOnBlur: false }); $('#searcher').focus(); });
/** * Copyright 2016 aixigo AG * Released under the MIT license. * http://laxarjs.org/license */ /** * Allows to instantiate a mock implementations of {@link AxStorage}, compatible to the "axStorage" injection. * * @module widget_services_storage_mock */ import { create as createGlobalStorageMock } from './storage_mock'; /** * Creates a mock for the `axStorage` injection of a widget. * * @return {AxStorageMock} * a mock of `axStorage` that can be spied and/or mocked with additional items */ export function create() { const globalStorageMock = createGlobalStorageMock(); const namespace = 'mock'; const local = globalStorageMock.getLocalStorage( namespace ); const session = globalStorageMock.getSessionStorage( namespace ); /** * The AxStorageMock provides the same API as AxStorage, with the additional property * {@link #mockBackends} to inspect and/or simulate mock values in the storage backend. * * @name AxStorageMock * @constructor * @extends AxStorage */ return { local, session, /** * Provides access to the backing stores for `local` and `session` storage. * * Contains `local` and `session` store properties. The stores are plain objects whose properties * reflect any setItem/removeItem operations. When properties are set on a store, they are observed * by `getItem` calls on the corresponding axStorage API. * * @memberof AxStorageMock */ mockBackends: { local: globalStorageMock.mockBackends.local[ namespace ].store, session: globalStorageMock.mockBackends.session[ namespace ].store } }; }
import {appendHtml, combine} from './../util'; const ELEMENT_NAMES = { frameName: 'text-frame', messageName: 'text-message', indicatorName: 'text-indicator' }; let createElements = (container, names) => { const elements = '\ <div class="text-frame" id="' + names.frameName + '">\ <span class="text-message" id="' + names.messageName + '"></span>\ <span id="' + names.indicatorName + '">▼</span>\ </div>'; appendHtml(container, elements); } export default class TextOutput { constructor(parent, engine) { let elementNames = Object.assign(ELEMENT_NAMES, engine.overrides.customElementNames); if (!engine.overrides.useCustomElements) { createElements(parent, elementNames); } this._textMessages = []; this.engine = engine; this.textMessageFrame = document.getElementById(elementNames.frameName); this.textMessage = document.getElementById(elementNames.messageName); this.textIndicator = document.getElementById(elementNames.indicatorName) this.textMessageFrame.onclick = () => engine.drawMessages(); engine.clearText = combine(engine.clearText, this.clearText.bind(this)); engine.displayText = combine(engine.displayText, this.displayText.bind(this)); engine.drawMessages = combine(engine.drawMessages, this.drawMessages.bind(this)); engine.actionExecutor.registerAction("text", (options, engine, player, callback) => { engine.displayText(options.text.split("\n")); }, false, true); } clearText () { this._textMessages = []; this.textMessageFrame.classList.remove("in"); this.textMessage.innerHTML = ""; this.textIndicator.classList.remove("in"); this.engine.unpause(); } displayText (text) { this._textMessages = this._textMessages.concat(text); } drawMessages () { if (this._textMessages.length > 0) { this.engine.pause(); const text = this._textMessages.splice(0, 1)[0]; this.textMessage.innerHTML = text; if (!("in" in this.textMessageFrame.classList)) { this.textMessageFrame.classList.add("in"); } if (this._textMessages.length >= 1) { this.textIndicator.classList.add("in"); } else { this.textIndicator.classList.remove("in"); } } else { this.clearText(); } } }
//= require sencha_touch/sencha-touch //= require_directory ./sencha_touch/app //= require_tree ./sencha_touch/app/models //= require_tree ./sencha_touch/app/stores //= require_tree ./sencha_touch/app/controllers //= require_tree ./sencha_touch/app/views
;(function() { function ToerismeApp(id, parentContainer) { this.API_URL = 'https://datatank.stad.gent/4/toerisme/visitgentevents.json'; this.id = id; this.parentContainer = parentContainer; this.loadData = function() { var that = this; var xhr = new XMLHttpRequest(); xhr.open('get', this.API_URL, true); xhr.responseType = 'json'; xhr.onload = function() { if(xhr.status == 200) { var data = (!xhr.responseType)?JSON.parse(xhr.response):xhr.response; var id = 1; var tempStr = ''; for(i=0; i<20; i++) { var title = data[i].title; var contact = data[i].contact[0]; //var website = contact.website[0]; //var weburl = website.url; var images = data[i].images[0]; var language = data[i].language; var website = ''; if(contact.website){ website = contact.website[0].url; //console.log(website); } if(language == 'nl'){ tempStr += '<div class="row row_events">'; tempStr += '<a href="http://' + website +'" target="_blank";>'; tempStr += '<div class="col-xs-6"><div class="div_image" style="background: url(' + images +') no-repeat center ;background-size:cover;"></div></div>'; tempStr += '<div class="col-xs-6"><h4>' + title + '</h4>'; tempStr += '<p>Adres: ' + contact.street + ' nr ' + contact.number + '<br> Stad: ' + contact.city +'</p>'; tempStr += '</div>'; /* einde adres */ tempStr += '</a>'; tempStr += '<a class="link_heart" id="myDIV'+[i]+'" alt="Add to favorites" title="Add to favorites" onclick="myFunction('+[i]+')" ><span class="glyphicon glyphicon-heart-empty"></span></a>'; tempStr += '</div>';/* einde row */ }else{}; } that.parentContainer.innerHTML = tempStr; } else { console.log('xhr.status'); } } xhr.onerror = function() { console.log('Error'); } xhr.send(); }; this.updateUI = function() { }; this.toString = function() { return `ToerismeApp with id: ${this.id}`; }; }; var ww1 = new ToerismeApp(1, document.querySelector('.sidebar')); ww1.loadData(); console.log(ww1.toString()); })(); function myFunction(id){ document.getElementById("myDIV"+id).classList.toggle("link_heart-select"); }
module.exports = "module-one-A-model";
$(function () { 'use strict'; const notificationType = { success: 'Success', error: 'Error', info: 'Info' }, notificationTypeClass = { success: 'toast-success', info: 'toast-info', error: 'toast-error' }; function initSignalR() { let connection = $.connection, hub = connection.notificationHub; hub.client.toast = (message, dellay, type) => { console.log('CALLEEEEEEEEEEEED') if (type === notificationType.success) { Materialize.toast(message, dellay, notificationTypeClass.success) } else if (type === notificationType.info) { Materialize.toast(message, dellay, notificationTypeClass.info) } else { Materialize.toast(message, dellay, notificationTypeClass.error) } }; connection.hub.start().done(() => hub.server.init()); } initSignalR(); }());
/** * Ensures that the callback pattern is followed properly * with an Error object (or undefined or null) in the first position. */ 'use strict' // ------------------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------------------ /** * Determine if a node has a possiblity to be an Error object * @param {ASTNode} node ASTNode to check * @returns {boolean} True if there is a chance it contains an Error obj */ function couldBeError (node) { let exprs switch (node.type) { case 'Identifier': case 'CallExpression': case 'NewExpression': case 'MemberExpression': case 'TaggedTemplateExpression': case 'YieldExpression': return true // possibly an error object. case 'AssignmentExpression': return couldBeError(node.right) case 'SequenceExpression': exprs = node.expressions return exprs.length !== 0 && couldBeError(exprs[exprs.length - 1]) case 'LogicalExpression': return couldBeError(node.left) || couldBeError(node.right) case 'ConditionalExpression': return couldBeError(node.consequent) || couldBeError(node.alternate) default: return node.value === null } } // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ module.exports = { meta: { type: 'suggestion', docs: { url: 'https://github.com/standard/eslint-plugin-standard#rules-explanations' } }, create: function (context) { const callbackNames = context.options[0] || ['callback', 'cb'] function isCallback (name) { return callbackNames.indexOf(name) > -1 } return { CallExpression: function (node) { const errorArg = node.arguments[0] const calleeName = node.callee.name if (errorArg && !couldBeError(errorArg) && isCallback(calleeName)) { context.report(node, 'Unexpected literal in error position of callback.') } } } } }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > The Date.prototype.getMinutes property "length" has { ReadOnly, DontDelete, DontEnum } attributes es5id: 15.9.5.20_A3_T1 description: Checking ReadOnly attribute ---*/ x = Date.prototype.getMinutes.length; Date.prototype.getMinutes.length = 1; if (Date.prototype.getMinutes.length !== x) { $ERROR('#1: The Date.prototype.getMinutes.length has the attribute ReadOnly'); }
module.exports = function(sails) { var Agenda = require('agenda'), util = require('util'), _ = require('lodash'), os = require("os"), agenda = new Agenda() agenda.sails = sails; var stopServer = function() { agenda.stop(function() { console.log("agenda stopped"); }); }; sails.on("lower", stopServer); sails.on("lowering", stopServer); // return hook return { // expose agenda in sails.hooks.jobs.agenda jobs: agenda, // Defaults config defaults: { jobs: { "globalJobsObjectName": "Jobs", "jobsDirectory": "api/jobs", "db": { "address" : "localhost:27017/jobs", "collection" : "agendaJobs" }, "name": os.hostname() + '-' + process.pid, "processEvery": "1 minutes", "maxConcurrency": 20, "defaultConcurrency": 5, "defaultLockLifetime": 10000, } }, // Runs automatically when the hook initializes initialize: function (cb) { var hook = this , config = sails.config.jobs // init agenda agenda .database(config.db.address, config.db.collection) .name(config.name) .processEvery(config.processEvery) .maxConcurrency(config.maxConcurrency) .defaultConcurrency(config.defaultConcurrency) .defaultLockLifetime(config.defaultLockLifetime) global[config.globalJobsObjectName] = agenda; // Enable jobs using coffeescript try { require('coffee-script/register'); } catch(e0) { try { var path = require('path'); var appPath = sails.config.appPath || process.cwd(); require(path.join(appPath, 'node_modules/coffee-script/register')); } catch(e1) { sails.log.verbose('Please run `npm install coffee-script` to use coffescript (skipping for now)'); } } // Find all jobs var jobs = require('include-all')({ dirname : sails.config.appPath + '/' + config.jobsDirectory, filter : /(.+Job).(?:js|coffee)$/, excludeDirs : /^\.(git|svn)$/, optional : true }); // init jobs hook.initJobs(jobs); // Lets wait on some of the sails core hooks to // finish loading before we load our hook // that talks about cats. var eventsToWaitFor = []; if (sails.hooks.orm) eventsToWaitFor.push('hook:orm:loaded'); if (sails.hooks.pubsub) eventsToWaitFor.push('hook:pubsub:loaded'); sails.after(eventsToWaitFor, function(){ // if (jobs.length > 0) { // start agenda agenda.start(); sails.log.verbose("sails jobs started") // } // Now we will return the callback and our hook // will be usable. return cb(); }); }, /** * Function that initialize jobs */ initJobs: function(jobs, namespace) { var hook = this if (!namespace) namespace = "jobs"; sails.log.verbose("looking for job in " + namespace + "... ") _.forEach(jobs, function(job, name){ if (typeof job === 'function') { var log = "" , _job = job(agenda) , _dn = namespace + "." + name , _name = _job.name || _dn.substr(_dn.indexOf('.') +1); if (_job.disabled) { log += "-> Disabled Job '" + _name + "' found in '" + namespace + "." + name + "'."; } else { var options = (typeof _job.options === 'object')?_job.options:{} , freq = typeof _job.frequency == 'undefined'?sails.config.jobs.processEvery:_job.frequency , error = false; if (typeof _job.run === "function") agenda.define(_name, options, _job.run); log += "-> Job '" + _name + "' found in '" + namespace + "." + name + "', defined in agenda"; if (typeof freq === 'string') { freq = freq.trim().toLowerCase(); if (freq.indexOf('every') == 0) { var interval = freq.substr(6).trim(); agenda.every(interval, _name, _job.data); log += " and will run " + freq; } else if (freq.indexOf('schedule') == 0) { var when = freq.substr(9).trim(); agenda.schedule(when, _name, _job.data); log += " and scheduled " + when; } else if (freq === 'now') { agenda.now(_name, _job.data); log += " and started"; } else { error = true; log += " but frequency is not supported"; } } } log += "."; if (error) sails.log.error(log); else sails.log.verbose(log); } else { hook.initJobs(job, namespace + "." + name); } }) } } };
export class NewForm { update() { } }
var grunt = require('grunt'); var fs = require('fs'); var gruntTextReplace = require('../lib/grunt-match-replace'); var replace = function (settings) { return gruntTextReplace.replace(settings); }; exports.textReplace = { 'Test error handling': { setUp: function (done) { grunt.file.copy('test/text_files/test.txt', 'test/temp/testA.txt'); grunt.file.copy('test/text_files/test.txt', 'test/temp/testB.txt'); done(); }, tearDown: function (done) { fs.unlinkSync('test/temp/testA.txt'); fs.unlinkSync('test/temp/testB.txt'); fs.rmdirSync('test/temp'); done(); }, 'Test no destination found': function (test) { var warnCountBefore = grunt.fail.warncount; replace({ src: 'test/temp/testA.txt', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/testA.txt', overwrite: true, replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/testA.txt', dest: 'test/temp/', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); test.done(); }, 'Test no replacements found': function (test) { var warnCountBefore = grunt.fail.warncount; replace({ src: 'test/temp/testA.txt', dest: 'test/temp/' }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/testA.txt', dest: 'test/temp/', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); test.done(); }, 'Test overwrite failure': function (test) { var warnCountBefore = grunt.fail.warncount; replace({ src: 'test/temp/testA.txt', dest: 'test/temp/', overwrite: true, replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/*', overwrite: true, replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/testA.txt', overwrite: true, replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); test.done(); }, 'Test destination error': function (test) { var warnCountBefore = grunt.fail.warncount; replace({ src: 'test/temp/*', dest: 'test/temp', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 1); replace({ src: 'test/temp/*', dest: 'test/temp/testA.txt', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 2); replace({ src: 'test/temp/testA.txt', dest: 'test/temp/testB.txt', replacements: [{ from: 'Hello', to: 'Good bye' }] }); test.equal(grunt.fail.warncount - warnCountBefore, 2); test.done(); } } };
var sourceFolder = 'src', destFolder = 'public', configFolder = 'config'; module.exports = { folders: { source: sourceFolder, dest: destFolder }, files: { scripts: [ `${sourceFolder}/js/utils.js`, `${sourceFolder}/js/sprites/weapon.js`, `${sourceFolder}/js/sprites/hook.js`, `${sourceFolder}/js/sprites/enemy.js`, `${sourceFolder}/js/sprites/**/*.js`, `${sourceFolder}/js/map.js`, `${sourceFolder}/js/ui/**/*.js`, `${sourceFolder}/js/states/**/*.js`, `${sourceFolder}/js/**/*.js` ], templates: `${sourceFolder}/templates/**/*.html`, libs: [ 'node_modules/phaser/dist/phaser.js', 'node_modules/stats.js/build/stats.min.js' ], styles: `${sourceFolder}/styles/**/*.css`, images: `${sourceFolder}/images/**/*.*`, sounds: `${sourceFolder}/sounds/**/*.*`, json: `${sourceFolder}/json/**/*.*`, fonts: `${sourceFolder}/fonts/**/*.*`, cname: `${configFolder}/CNAME` }, scripts: { destFolder: `${destFolder}/js`, outFile: 'index.js' }, libs: { destFolder: `${destFolder}/js`, outFile: 'libs.js' }, styles: { destFolder: `${destFolder}/css`, outFile: 'index.css' }, images: { destFolder: `${destFolder}/images` }, sounds: { destFolder: `${destFolder}/sounds` }, json: { destFolder: `${destFolder}/json` }, fonts: { destFolder: `${destFolder}/fonts` }, server: { root: destFolder, livereload: true } };
module.exports = { server: { host: '0.0.0.0', port: 3000 }, database: { host: '158.85.190.240', port: 27017, db: 'hackathon', username: 'administrator', password: 'hunenokGaribaldi9' } };
'use strict'; /* istanbul ignore next */ /* eslint-disable no-console */ /** * Handle failures in the application by terminating. * @param {Exception} err - Exception to handle. */ module.exports = (err) => { console.log(err); console.log(err.stack); process.exit(-1); };
import Omi from 'omi/dist/omi' import { CellsTitle, Cells, CellHeader, CellBody, CellFooter } from '../cell' Omi.makeHTML('CellsTitle', CellsTitle); Omi.makeHTML('Cells', Cells); Omi.makeHTML('CellHeader', CellHeader); Omi.makeHTML('CellBody', CellBody); Omi.makeHTML('CellFooter', CellFooter); export default class List extends Omi.Component{ constructor(data) { super(data); } render(){ return ` <div> <CellsTitle data-title={{title}} /> <Cells slot-index="0"> <div> {{#items}} <{{#link}}a href={{link}} {{/link}}{{^link}}div{{/link}} class="weui-cell {{#link}}weui-cell_access{{/link}}"> {{#imageUrl}} <CellHeader> <img style="width:20px;margin-right:5px;display:block" src={{imageUrl}} /> </CellHeader> {{/imageUrl}} <CellBody slot-index="0" > <p>{{{title}}}</p> </CellBody> <CellFooter slot-index="1"> <span>{{value}}</span> </CellFooter> </{{#link}}a{{/link}}{{^link}}div{{/link}}> {{/items}} </div> </Cells> </div> `; } }
/** @module ember-flexberry-gis */ import Ember from 'ember'; /** Class implementing base stylization for markers. @class BaseMarkerStyle */ export default Ember.Object.extend({ /** Gets default style settings. @method getDefaultStyleSettings @return {Object} Hash containing default style settings. */ getDefaultStyleSettings() { return null; }, /** Applies layer-style to the specified leaflet layer. @method renderOnLeafletMarker @param {Object} options Method options. @param {<a =ref="http://leafletjs.com/reference-1.2.0.html#marker">L.Marker</a>} options.marker Leaflet marker to which marker-style must be applied. @param {Object} options.style Hash containing style settings. */ renderOnLeafletMarker({ marker, style }) { throw `Method 'renderOnLeafletMarker' isn't implemented in 'base' marker-style`; }, /** Renderes layer-style preview on the specified canvas element. @method renderOnCanvas @param {Object} options Method options. @param {<a =ref="https://developer.mozilla.org/ru/docs/Web/HTML/Element/canvas">Canvas</a>} options.canvas Canvas element on which marker-style preview must be rendered. @param {Object} options.style Hash containing style settings. @param {Object} [options.target = 'preview'] Render target ('preview' or 'legend'). */ renderOnCanvas({ canvas, style, target }) { throw `Method 'renderOnCanvas' isn't implemented in 'base' marker-style`; } });
(() => { 'use strict'; angular.module('RestTestApp') .config(($urlRouterProvider, $locationProvider) => { $locationProvider.html5Mode(true); }) .config(function(RestTestStateConfigProvider) { RestTestStateConfigProvider.initialize(); }); })();
/* * * The MIT License * * Copyright (c) 2015, Sebastian Sdorra * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; angular.module('sample-01', ['adf', 'LocalStorageModule']) .controller('sample01Ctrl', function($scope, localStorageService){ var name = 'sample-01'; var model;// = localStorageService.get(name); if (!model) { // set default model for demo purposes model = { title: "Sample 01", structure: "4-4-4", rows: [{ columns: [{ styleClass: "col-md-4", widgets: [{ type: "Pie" }] }, { styleClass: "col-md-4", widgets: [{ type: "Pie" }] },{ styleClass: "col-md-4", widgets: [{ type: "Pie" }] }] }] }; } $scope.name = name; $scope.model = model; $scope.collapsible = false; $scope.maximizable = false; $scope.$on('adfDashboardChanged', function (event, name, model) { localStorageService.set(name, model); }); });
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var app = new EmberApp(); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/modernizr/modernizr.js'); module.exports = app.toTree();
"use strict"; var CropTouch = (function () { function CropTouch(x, y, id) { this.id = id || 0; this.x = x || 0; this.y = y || 0; this.dragHandle = null; } return CropTouch; }()); exports.CropTouch = CropTouch; //# sourceMappingURL=cropTouch.js.map
(function () { 'use strict'; angular .module('Debug', ['pullrefresh']); })();
module.exports = function(knex) { describe('Transactions', function() { it('should be able to commit transactions', function(ok) { var id = null; return knex.transaction(function(t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User', email:'transaction-test@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date() }).then(function(resp) { return knex('test_table_two').transacting(t).insert({ account_id: (id = resp[0]), details: '', status: 1 }); }).then(function() { t.commit('Hello world'); }); }).then(function(commitMessage) { expect(commitMessage).to.equal('Hello world'); return knex('accounts').where('id', id).select('first_name'); }).then(function(resp) { expect(resp).to.have.length(1); }).otherwise(function(err) { console.log(err); }); }); it('should be able to rollback transactions', function(ok) { var id = null; var err = new Error('error message'); return knex.transaction(function(t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User2', email:'transaction-test2@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date() }).then(function(resp) { return knex('test_table_two').transacting(t).insert({ account_id: (id = resp[0]), details: '', status: 1 }); }).then(function() { t.rollback(err); }); }).otherwise(function(msg) { expect(msg).to.equal(err); return knex('accounts').where('id', id).select('first_name'); }).then(function(resp) { expect(resp).to.be.empty; }); }); }); };
var path = require('path'); var webpack = require('webpack'); var _ = require('lodash'); var baseConfig = require('./base'); // Add needed plugins here var BowerWebpackPlugin = require('bower-webpack-plugin'); var config = _.merge({ entry: [ 'webpack-dev-server/client?http://127.0.0.1:8000', 'webpack/hot/only-dev-server', './src/components/run' ], cache: true, devtool: 'eval', plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new BowerWebpackPlugin({ searchResolveModulesDirectories: false }) ] }, baseConfig); // Add needed loaders config.module.loaders.push({ test: /\.(js|jsx)$/, loader: 'react-hot!babel-loader', include: path.join(__dirname, '/../src') }); module.exports = config;
var http = require('http') var https = require('https') var corsify = require('corsify') var collect = require('stream-collector') var pump = require('pump') var iterate = require('random-iterate') var limiter = require('size-limit-stream') var eos = require('end-of-stream') var flushHeaders = function (res) { if (res.flushHeaders) { res.flushHeaders() } else { if (!res._header) res._implicitHeader() res._send('') } } module.exports = function (opts) { var channels = {} var maxBroadcasts = (opts && opts.maxBroadcasts) || Infinity var get = function (channel) { if (channels[channel]) return channels[channel] channels[channel] = {name: channel, subscribers: []} return channels[channel] } var cors = corsify({ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE", "Access-Control-Allow-Headers": "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }) var onRequest = cors(function (req, res) { if (req.url === '/') { res.end(JSON.stringify({name: 'signalhub', version: require('./package').version}, null, 2) + '\n') return } if (req.url.slice(0, 4) !== '/v1/') { res.statusCode = 404 res.end() return } var name = req.url.slice(4).split('?')[0] if (req.method === 'POST') { collect(pump(req, limiter(64 * 1024)), function (err, data) { if (err) return res.end() if (!channels[name]) return res.end() var channel = get(name) server.emit('publish', channel.name, data) data = Buffer.concat(data).toString() var ite = iterate(channel.subscribers) var next var cnt = 0 while ((next = ite()) && cnt++ < maxBroadcasts) { next.write('data: ' + data + '\n\n') } res.end() }) return } if (req.method === 'GET') { res.setHeader('Content-Type', 'text/event-stream; charset=utf-8') var app = name.split('/')[0] var channelNames = name.slice(app.length + 1) channelNames.split(',').forEach(function (channelName) { var channel = get(app + '/' + channelName) server.emit('subscribe', channel.name) channel.subscribers.push(res) eos(res, function () { var i = channel.subscribers.indexOf(res) if (i > -1) channel.subscribers.splice(i, 1) if (!channel.subscribers.length && channel === channels[channel.name]) delete channels[channel.name] }) }) flushHeaders(res) return } res.statusCode = 404 res.end() }) var server = ((opts && opts.key) ? https : http).createServer(opts) server.on('request', onRequest) return server }
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users'); var centers = require('../../app/controllers/centers'); // Centers Routes app.route('/centers') .get(centers.list) app.route('/centers') .get(centers.create) app.route('/centers/:centerId') .get(centers.read) .put(users.requiresLogin, centers.hasAuthorization, centers.update) .delete(users.requiresLogin, centers.hasAuthorization, centers.delete); // Finish by binding the Center middleware app.param('centerId', centers.centerByID); };
const path = require('path') const merge = require('webpack-merge') const webpack = require('webpack') const baseWebpackConfig = require('./webpack.base.config') const ExtractTextPlugin = require("extract-text-webpack-plugin") const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') function resolve (dir) { return path.join(__dirname, '..', dir) } module.exports = merge(baseWebpackConfig, { output: { path: resolve('dist'), filename: '[name].[hash].js' }, plugins: [ // optimize css for production new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }), new ExtractTextPlugin('style.[hash].css'), // split vendor js into separate file new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module) { // this assumes your vendor imports exist in the node_modules directory return module.context && module.context.indexOf("node_modules") !== -1; } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] }), ] })
export default { html: ` <p>42</p> <p>42</p> `, async test({ assert, component, target }) { await component.updateStore(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>42</p>'); await component.updateStore(33); assert.htmlEqual(target.innerHTML, '<p>33</p><p>42</p>'); await component.updateStore(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>42</p>'); await component.updateVar(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>undefined</p>'); await component.updateVar(33); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>33</p>'); await component.updateVar(undefined); assert.htmlEqual(target.innerHTML, '<p>undefined</p><p>undefined</p>'); } };
import React from 'react'; import { applyRouterMiddleware, Router, Route } from 'dva/router'; import { useScroll } from 'react-router-scroll'; import App from '@/app/App'; function RouterConfig({ history }) { return ( <Router history={history} render={applyRouterMiddleware(useScroll())}> <Route path="/" component={App}></Route> </Router> ); } export default RouterConfig;
import React, { Component, PropTypes } from 'react'; import { Image } from 'react-bootstrap'; require('./styles.scss'); class SocialBar extends Component { constructor(props) { super(props); } render() { const { icon, url } = this.props; return ( <a href={url} target="_blank"> <Image src={icon} className="profile-header-social-icon" /> </a> ); } } SocialBar.propTypes = { children: PropTypes.any, icon: PropTypes.any.isRequired, url: PropTypes.string.isRequired, }; export default SocialBar;
'use strict'; describe('heroList', function(){ //Load module that contains the heroList component beforeEach(module('heroList')); describe('HeroListController', function(){ it('should create a `heroes` model with 6 heroes', inject(function($componentController){ var ctrl = $componentController('heroList'); expect(ctrl.heroes.length).toBe(6); })); }); });
document.getElementById('input_search').onfocus = function () { document.getElementById('search').classList.add('activeSearch'); }; document.getElementById('input_search').onblur = function () { document.getElementById('search').classList.remove('activeSearch'); }; try { window.$ = window.jQuery = require('jquery'); require('./navbar'); require('./horizontalScroll'); } catch (e) {}
/// <reference path="lib/jquery-2.0.3.js" /> define(["httpRequester"], function (httpRequester) { function getStudents() { var url = this.url + "api/students/"; return httpRequester.getJSON(url); } function getMarksByStudentId(studentId) { var url = this.url + "api/students/" + studentId + "/marks/"; return httpRequester.getJSON(url); } return { students: getStudents, marks: getMarksByStudentId, url: this.url } });
/** * WhatsApp service provider */ module.exports = { popupUrl: 'whatsapp://send?text={title}%0A{url}', popupWidth: 600, popupHeight: 450 };
var path = require('path'), HtmlReporter = require('protractor-html-screenshot-reporter'); exports.config = { chromeDriver: 'node_modules/chromedriver/bin/chromedriver', // seleniumAddress: 'http://localhost:4444/wd/hub', // Boolean. If true, Protractor will connect directly to the browser Drivers // at the locations specified by chromeDriver and firefoxPath. Only Chrome // and Firefox are supported for direct connect. directConnect: true, // Use existing selenium local/remote // seleniumAddress: http://localhost:4444/wd/hub // When run without a command line parameter, all suites will run. If run // with --suite=login only the patterns matched by the specified suites will // run. // @todo specs: ['specs/aui-login.js'], // The timeout in milliseconds for each script run on the browser. This should // be longer than the maximum time your application needs to stabilize between // tasks. allScriptsTimeout: 20000, baseUrl: 'http://localhost:9010', multiCapabilities: [{ 'browserName': 'chrome' }, { 'browserName': 'firefox' }], onPrepare: function() { // Add a screenshot reporter and store screenshots to `result/screnshots`: jasmine.getEnv().addReporter(new HtmlReporter({ baseDirectory: './result/screenshots', takeScreenShotsOnlyForFailedSpecs: true, preserveDirectory: true, docTitle: 'E2E Result', docName: 'index.html', pathBuilder: function pathBuilder(spec, descriptions, results, capabilities) { var currentDate = new Date(), dateString = currentDate.getFullYear() + '-' + currentDate.getMonth() + '-' + currentDate.getDate(); return path.join(dateString, capabilities.caps_.browserName, descriptions.join('-')); } })); } };
/** * format currency * @ndaidong **/ const { isNumber, } = require('bellajs'); const formatCurrency = (num) => { const n = Number(num); if (!n || !isNumber(n) || n < 0) { return '0.00'; } return n.toFixed(2).replace(/./g, (c, i, a) => { return i && c !== '.' && (a.length - i) % 3 === 0 ? ',' + c : c; }); }; module.exports = formatCurrency;
import React from 'react' import PropTypes from 'prop-types' import FormGroup from '../forms/FormGroup' import InputColor from '../forms/InputColor' const ColorStackOption = ({ label, name, value, definitions, required, onChange, error }) => { // default value may be null if (value === null) { value = '' } return ( <FormGroup label={label} htmlFor={name} error={error} required={required}> <InputColor name={name} id={name} value={value} defaultValue={definitions.default} onChange={onChange} /> </FormGroup> ) } ColorStackOption.propTypes = { label: PropTypes.string.isRequired, name: PropTypes.string.isRequired, definitions: PropTypes.object.isRequired, required: PropTypes.bool, value: PropTypes.string, onChange: PropTypes.func, error: PropTypes.string } export default ColorStackOption
const td = require('testdouble'); const expect = require('../../../../helpers/expect'); const RSVP = require('rsvp'); const Promise = RSVP.Promise; const adbPath = 'adbPath'; const deviceUUID = 'uuid'; const apkPath = 'apk-path'; const spawnArgs = [adbPath, ['-s', deviceUUID, 'install', '-r', apkPath]]; describe('Android Install App - Device', () => { let installAppDevice; let spawn; beforeEach(() => { let sdkPaths = td.replace('../../../../../lib/targets/android/utils/sdk-paths'); td.when(sdkPaths()).thenReturn({ adb: adbPath }); spawn = td.replace('../../../../../lib/utils/spawn'); td.when(spawn(...spawnArgs)).thenReturn(Promise.resolve({ code: 0 })); installAppDevice = require('../../../../../lib/targets/android/tasks/install-app-device'); }); afterEach(() => { td.reset(); }); it('calls spawn with correct arguments', () => { td.config({ ignoreWarnings: true }); td.when(spawn(), { ignoreExtraArgs: true }) .thenReturn(Promise.resolve({ code: 0 })); return installAppDevice(deviceUUID, apkPath).then(() => { td.verify(spawn(...spawnArgs)); td.config({ ignoreWarnings: false }); }); }); it('resolves with object containing exit code from spawned process', () => { return expect(installAppDevice(deviceUUID, apkPath)) .to.eventually.contain({ code: 0 }); }); it('bubbles up error message when spawn rejects', () => { td.when(spawn(...spawnArgs)).thenReturn(Promise.reject('spawn error')); return expect(installAppDevice(deviceUUID, apkPath)) .to.eventually.be.rejectedWith('spawn error'); }); });
app.config(function ($routeProvider, $locationProvider) { "use strict"; $routeProvider.when('/', { controller: 'HomeController', templateUrl: '/static/apps/main/views/home.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, current: function (SprintService) { var sprints = SprintService.listSprints(); } } }).when('/tasks/', { controller: 'TaskController', templateUrl: '/static/apps/main/views/tasks.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, task: function () { return false; } } }).when('/tasks/:taskid', { controller: 'TaskController', templateUrl: '/static/apps/main/views/task.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, task: function (TaskService, $route) { return TaskService.getTask($route.current.params.taskid); } } }).when('/sprints/', { controller: 'SprintController', templateUrl: '/static/apps/main/views/sprints.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, sprint: function () { return false; } } }).when('/sprints/:sprintid', { controller: 'SprintController', templateUrl: '/static/apps/main/views/sprint.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); }, sprint: function (SprintService, $route) { return $route.current.params.sprintid; } } }).when('/categories/', { controller: 'CategoryController', templateUrl: '/static/apps/main/views/categories.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); } } }).when('/stats/', { controller: 'StatsController', templateUrl: '/static/apps/main/views/stats.html', resolve: { tasks: function (TaskService) { return TaskService.listTasks(); }, categories: function (CategoryService) { return CategoryService.listCategories(); }, sprints: function (SprintService) { return SprintService.listSprints(); } } }).otherwise({redirectTo: '/'}); });
import React from 'react'; import { getCategoryGroups } from '../selectors/categoryGroups'; import { getCategoriesByGroupId } from '../selectors/categories'; import { getSelectedMonthBudgetItemsByCategoryId, getBudgetItemsSumUpToSelectedMonthByCategoryId } from '../selectors/budgetItems'; import { getTransactionsSumUpToSelectedMonthByCategoryId, getSelectedMonthActivityByCategoryId } from '../selectors/transactions'; import {connect} from 'react-redux'; import CategoryRow from './CategoryRow'; import CategoryGroupRow from './CategoryGroupRow'; import ui from 'redux-ui'; @ui({ state: { editingCategoryId: undefined } }) class BudgetTable extends React.Component { static propTypes = { categoryGroups: React.PropTypes.array.isRequired, categoriesByGroupId: React.PropTypes.object.isRequired, getSelectedMonthActivityByCategoryId: React.PropTypes.object.isRequired, getSelectedMonthBudgetItemsByCategoryId: React.PropTypes.object.isRequired, transactionsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired, budgetItemsSumUpToSelectedMonthByCategoryId: React.PropTypes.object.isRequired } render() { const rows = []; this.props.categoryGroups.forEach(cg => { rows.push(<CategoryGroupRow key={"cg"+cg.id} name={cg.name} />); if (this.props.categoriesByGroupId[cg.id]) { this.props.categoriesByGroupId[cg.id].forEach(c => { rows.push(<CategoryRow key={"c"+c.id} category={c} budgetItem={this.props.getSelectedMonthBudgetItemsByCategoryId[c.id]} activity={this.props.getSelectedMonthActivityByCategoryId[c.id]} available={(this.props.budgetItemsSumUpToSelectedMonthByCategoryId[c.id] || 0) + (this.props.transactionsSumUpToSelectedMonthByCategoryId[c.id] || 0)} />); }); } }); return ( <table className="table"> <thead> <tr> <th>Category</th> <th>Budgeted</th> <th>Activity</th> <th>Available</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } } const mapStateToProps = (state) => ({ categoryGroups: getCategoryGroups(state), categoriesByGroupId: getCategoriesByGroupId(state), getSelectedMonthActivityByCategoryId: getSelectedMonthActivityByCategoryId(state), getSelectedMonthBudgetItemsByCategoryId: getSelectedMonthBudgetItemsByCategoryId(state), transactionsSumUpToSelectedMonthByCategoryId: getTransactionsSumUpToSelectedMonthByCategoryId(state), budgetItemsSumUpToSelectedMonthByCategoryId: getBudgetItemsSumUpToSelectedMonthByCategoryId(state) }); export default connect(mapStateToProps)(BudgetTable);
'use strict'; module.exports = { db: 'mongodb://localhost/equinix-test', port: 3001, app: { title: 'Equinix - Test Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
import { injectReducer } from '../../../../store/reducers' export default (store) => ({ path: 'admin/positions/add', /* Async getComponent is only invoked when route matches */ getComponent (nextState, cb) { /* Webpack - use 'require.ensure' to create a split point and embed an async module loader (jsonp) when bundling */ require.ensure([], (require) => { /* Webpack - use require callback to define dependencies for bundling */ const AddPosition = require('./AddPosition.component').default // const reducer = null; /* Add the reducer to the store on key 'counter' */ // injectReducer(store, { key: 'addPositions', reducer }) /* Return getComponent */ cb(null, AddPosition) /* Webpack named bundle */ }, 'addPositions') } })
'use strict'; var fetchUrl = require('fetch').fetchUrl; var packageInfo = require('../package.json'); var httpStatusCodes = require('./http.json'); var urllib = require('url'); var mime = require('mime'); // Expose to the world module.exports.resolve = resolve; module.exports.removeParams = removeParams; /** * Resolves an URL by stepping through all redirects * * @param {String} url The URL to be checked * @param {Object} options Optional options object * @param {Function} callback Callback function with error and url */ function resolve(url, options, callback) { var urlOptions = {}; if (typeof options == 'function' && !callback) { callback = options; options = undefined; } options = options || {}; urlOptions.method = options.method ||  'HEAD'; urlOptions.disableGzip = true; // no need for gzipping with HEAD urlOptions.asyncDnsLoookup = true; urlOptions.timeout = options.timeout ||  10000; urlOptions.userAgent = options.userAgent ||  (packageInfo.name + '/' + packageInfo.version + ' (+' + packageInfo.homepage + ')'); urlOptions.removeParams = [].concat(options.removeParams ||  [/^utm_/, 'ref']); urlOptions.agent = options.agent || false; urlOptions.rejectUnauthorized = false; urlOptions.headers = options.headers || {}; urlOptions.maxRedirects = options.maxRedirects || 10; fetchUrl(url, urlOptions, function(error, meta) { var err, url; if (error) { err = new Error(error.message || error); err.statusCode = 0; return callback(err); } if (meta.status != 200) { err = new Error('Server responded with ' + meta.status + ' ' + (httpStatusCodes[meta.status] || 'Invalid request')); err.statusCode = meta.status; return callback(err); } url = meta.finalUrl; if (urlOptions.removeParams && urlOptions.removeParams.length) { url = removeParams(url, urlOptions.removeParams); } var fileParams = detectFileParams(meta); return callback(null, url, fileParams.filename, fileParams.contentType); }); } function detectFileParams(meta) { var urlparts = urllib.parse(meta.finalUrl); var filename = (urlparts.pathname || '').split('/').pop(); var contentType = (meta.responseHeaders['content-type'] || 'application/octet-stream').toLowerCase().split(';').shift().trim(); var fileParts; var extension = ''; var contentExtension; (meta.responseHeaders['content-disposition'] || '').split(';').forEach(function(line) { var parts = line.trim().split('='), key = parts.shift().toLowerCase().trim(); if (key == 'filename') { filename = parts.join('=').trim(); } }); if (contentType == 'application/octet-stream') { contentType = mime.lookup(filename) || 'application/octet-stream'; } else { fileParts = filename.split('.'); if (fileParts.length > 1) { extension = fileParts.pop().toLowerCase(); } contentExtension = mime.extension(contentType); if (contentExtension && extension != contentExtension) { extension = contentExtension; } if (extension) { if (!fileParts.length ||  (fileParts.length == 1 && !fileParts[0])) { fileParts = ['index']; } fileParts.push(extension); } filename = fileParts.join('.'); } return { filename: filename, contentType: contentType }; } /** * Removes matching GET params from an URL * * @param {String} url URL to be checked * @param {Array} params An array of key matches to be removed * @return {String} URL */ function removeParams(url, params) { var parts, query = {}, deleted = false; parts = urllib.parse(url, true, true); delete parts.search; if (parts.query) { Object.keys(parts.query).forEach(function(key) { for (var i = 0, len = params.length; i < len; i++) { if (params[i] instanceof RegExp && key.match(params[i])) { deleted = true; return; } else if (key == params[i]) { deleted = true; return; } } query[key] = parts.query[key]; }); parts.query = query; } return deleted ? urllib.format(parts) : url; }
function move(Restangular, $uibModal, $q, notification, $state,$http) { 'use strict'; return { restrict: 'E', scope: { selection: '=', type: '@', ngConfirmMessage: '@', ngConfirm: '&' }, link: function(scope, element, attrs) { scope.myFunction = function(){ var spanDropdown = document.querySelectorAll('span.btn-group')[0]; spanDropdown.classList.add("open"); }; scope.icon = 'glyphicon-list'; if (attrs.type == 'move_to_package') scope.button = 'Move to Package'; var vods_array = []; $http.get('../api/vodpackages?package_type_id=3&package_type_id=4').then(function(response) { var data = response.data; for(var i=0;i<data.length;i++){ vods_array.push({name:data[i].package_name,id:data[i].id}) } }); scope.list_of_vods = vods_array; var newarray = []; scope.moveto = function () { var spanDropdown = document.querySelectorAll('span.btn-group')[0]; spanDropdown.classList.remove("open"); var array_of_selection_vod = scope.selection; scope.change = function(name,id){ scope.button = name; var id_of_selected_package = id; for(var j=0;j<array_of_selection_vod.length;j++){ newarray.push({package_id:id_of_selected_package,vod_id:array_of_selection_vod[j].values.id}) } if(newarray.length === 0) { notification.log('Sorry, you have not selected any Vod item.', { addnCls: 'humane-flatty-error' }); } else { $http.post("../api/package_vod", newarray).then(function (response,data, status, headers, config,file) { notification.log('Vod successfully added', { addnCls: 'humane-flatty-success' }); window.location.replace("#/vodPackages/edit/"+id_of_selected_package); },function (data, status, headers, config) { notification.log('Something Wrong', { addnCls: 'humane-flatty-error' }); }).on(error, function(error){ winston.error("The error during post request is ") }); } }; } }, template: '<div class="btn-group" uib-dropdown is-open="status.isopen"> ' + '<button ng-click="myFunction()" id="single-button" type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="disabled">' + '<span class="glyphicon {{icon}}"></span> {{button}} <span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu" uib-dropdown-menu role="menu" aria-labelledby="single-button">' + '<li role="menuitem" ng-click="change(choice.name,choice.id)" ng-repeat="choice in list_of_vods">' + '<p id="paragraph_vod" ng-click="moveto()">{{choice.name}}</p>' + '</li>' + '</ul>' + '</div>' }; } move.$inject = ['Restangular', '$uibModal', '$q', 'notification', '$state','$http']; export default move;
let mongoose = require('mongoose'); let URL = process.env.MONGO_URL || 'localhost'; let USER = process.env.MONGO_USR || ''; let PASSWORD = process.env.MONGO_PWD || ''; mongoose.connect(`mongodb://${USER}:${PASSWORD}@${URL}`); //TODO doens't work for localhost console.log(`Connecting to ${URL}...`); let db = mongoose.connection; db.on('error', (err) => console.error(err)); db.once('open', () => console.log('Connected!')); module.exports = db;
define([], function() { return Backbone.View.extend({ tagName: "a", className: "projectlink", attributes: { href: "#" }, template: _.template("<%- name %>"), events: { "click": "toggleSelection" }, initialize: function() { this.listenTo(this.model, "change:selected", function(m, selected) { this.$el.toggleClass("selected", selected); }); this.listenTo(this.model, "change:color", function(m, color) { this.$el.css("color", color); }); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this; }, toggleSelection: function() { this.model.set("selected", !this.model.get("selected")); return false; } }); });
'use strict'; (function() { describe('HomeController', function() { //Initialize global variables var scope, HomeController, myFactory; // Load the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); beforeEach(inject(function($controller, $rootScope) { scope = $rootScope.$new(); HomeController = $controller('HomeController', { $scope: scope }); })); it('should expose the authentication service', function() { expect(scope.authentication).toBeTruthy(); }); it('should see the result', function(){ scope.feedSrc = 'http://rss.cnn.com/rss/cnn_topstories.rss'; }); }); })();
'use strict'; module.exports = { images: { files: [ { cwd : 'src/assets/img/', src : '**/*', dest : '.build/img/', flatten : false, expand : true } ] }, config: { files: [ { cwd : 'src/config/', src : '**/*', dest : '.build/', flatten : false, expand : true } ] } };
// Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe". function findPalindromes(input) { var words = input.replace(/\W+/g, ' ').replace(/\s+/, ' ').trim().split(' '), palindromes = [], length = words.length, currentWord, i; for (i = 0; i < length; i += 1) { currentWord = words[i]; if (isPalindrome(currentWord) && currentWord.length != 1) { palindromes.push(currentWord); } } return palindromes.join(); } function isPalindrome(currentWord) { var length = currentWord.length, i; for (i = 0; i < length / 2; i += 1) { if (currentWord[i] != currentWord[currentWord.length - 1 - i]) { return false; } } return true; } var textSample = 'Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".'; console.log(findPalindromes(textSample));
// 19. Write a JavaScript function that returns array elements larger than a number. //two agrs - an array and a number to be larger than function isGreater(arr, num) { //set up an array to contain the results var resultArray = []; //iterate through based on length of the arr for(var i = 0; i < arr.length; i++) { //if current arr value is greater than num if(arr[i] > num) { //push result to resultArray resultArray.push(arr[i]); } } //log results console.log(resultArray); }
'use strict'; const signup = require('./signup'); const handler = require('feathers-errors/handler'); const notFound = require('./not-found-handler'); const logger = require('./logger'); module.exports = function() { // Add your custom middleware here. Remember, that // just like Express the order matters, so error // handling middleware should go last. const app = this; app.post('/signup', signup(app)); app.use(notFound()); app.use(logger(app)); app.use(handler()); };
'use strict'; var form = $('[name="uploadForm"]'); exports.getForm = function() { return form; }; exports.setDetails = function(url, id) { form.element(by.model('inputText')).sendKeys(url); form.element(by.model('snapshotId')).sendKeys(id); }; exports.submit = function() { form.element(by.css('[ng-click="upload()"]')).click(); };
module.exports = { 'resulting promise should be immediately rejected' : function(test) { var promise = promiseModule.reject('error'); test.ok(promise._status === -1); test.done(); }, 'resulting promise should be rejected with argument if argument is not a promise' : function(test) { promiseModule.reject('error').fail(function(error) { test.strictEqual(error, 'error'); test.done(); }); }, 'resulting promise should be rejected if argument is rejected' : function(test) { var defer = promiseModule.defer(); promiseModule.reject(defer.promise).fail(function(error) { test.strictEqual(error, 'error'); test.done(); }); defer.reject('error'); }, 'resulting promise should be rejected if argument is fulfilled' : function(test) { var defer = promiseModule.defer(); promiseModule.reject(defer.promise).fail(function(error) { test.strictEqual(error, 'val'); test.done(); }); defer.resolve('val'); } };
'use strict'; require('mocha'); const assert = require('assert'); const Generator = require('..'); let base; describe('.task', () => { beforeEach(() => { base = new Generator(); }); it('should register a task', () => { const fn = cb => cb(); base.task('default', fn); assert.equal(typeof base.tasks.get('default'), 'object'); assert.equal(base.tasks.get('default').callback, fn); }); it('should register a task with an array of dependencies', cb => { let count = 0; base.task('foo', next => { count++; next(); }); base.task('bar', next => { count++; next(); }); base.task('default', ['foo', 'bar'], next => { count++; next(); }); assert.equal(typeof base.tasks.get('default'), 'object'); assert.deepEqual(base.tasks.get('default').deps, ['foo', 'bar']); base.build('default', err => { if (err) return cb(err); assert.equal(count, 3); cb(); }); }); it('should run a glob of tasks', cb => { let count = 0; base.task('foo', next => { count++; next(); }); base.task('bar', next => { count++; next(); }); base.task('baz', next => { count++; next(); }); base.task('qux', next => { count++; next(); }); base.task('default', ['b*']); assert.equal(typeof base.tasks.get('default'), 'object'); base.build('default', err => { if (err) return cb(err); assert.equal(count, 2); cb(); }); }); it('should register a task with a list of strings as dependencies', () => { base.task('default', 'foo', 'bar', cb => { cb(); }); assert.equal(typeof base.tasks.get('default'), 'object'); assert.deepEqual(base.tasks.get('default').deps, ['foo', 'bar']); }); it('should run a task', cb => { let count = 0; base.task('default', cb => { count++; cb(); }); base.build('default', err => { if (err) return cb(err); assert.equal(count, 1); cb(); }); }); it('should throw an error when a task with unregistered dependencies is run', cb => { base.task('default', ['foo', 'bar']); base.build('default', err => { assert(err); cb(); }); }); it('should throw an error when a task does not exist', () => { return base.build('default') .then(() => { throw new Error('expected an error'); }) .catch(err => { assert(/registered/.test(err.message)); }); }); it('should emit task events', () => { const expected = []; base.on('task-registered', function(task) { expected.push(task.status + '.' + task.name); }); base.on('task-preparing', function(task) { expected.push(task.status + '.' + task.name); }); base.on('task', function(task) { expected.push(task.status + '.' + task.name); }); base.task('foo', cb => cb()); base.task('bar', ['foo'], cb => cb()); base.task('default', ['bar']); return base.build('default') .then(() => { assert.deepEqual(expected, [ 'registered.foo', 'registered.bar', 'registered.default', 'preparing.default', 'starting.default', 'preparing.bar', 'starting.bar', 'preparing.foo', 'starting.foo', 'finished.foo', 'finished.bar', 'finished.default' ]); }); }); it('should emit an error event when an error is returned in a task callback', cb => { base.on('error', err => { assert(err); assert.equal(err.message, 'This is an error'); }); base.task('default', cb => { return cb(new Error('This is an error')); }); base.build('default', err => { if (err) return cb(); cb(new Error('Expected an error')); }); }); it('should emit an error event when an error is thrown in a task', cb => { base.on('error', err => { assert(err); assert.equal(err.message, 'This is an error'); }); base.task('default', cb => { cb(new Error('This is an error')); }); base.build('default', err => { assert(err); cb(); }); }); it('should run dependencies before running the dependent task', cb => { const expected = []; base.task('foo', cb => { expected.push('foo'); cb(); }); base.task('bar', cb => { expected.push('bar'); cb(); }); base.task('default', ['foo', 'bar'], cb => { expected.push('default'); cb(); }); base.build('default', err => { if (err) return cb(err); assert.deepEqual(expected, ['foo', 'bar', 'default']); cb(); }); }); });
import containers from './containers' import ui from './ui' import App from './App' module.exports = {...containers, ...ui, App}
'use strict'; // Production specific configuration // ================================= module.exports = { // Server IP ip: process.env.OPENSHIFT_NODEJS_IP || process.env.IP || undefined, // Server port port: process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 8080, // MongoDB connection options mongo: { uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/spicyparty' } };
#!/usr/bin/env node 'use strict'; const fs = require('fs'); const repl = require('repl'); const program = require('commander'); const esper = require('..'); const Engine = esper.Engine; function enterRepl() { function replEval(cmd, context, fn, cb) { engine.evalDetatched(cmd).then(function(result) { cb(null, result); }, function(err) { console.log(err.stack); cb(null); }); } return repl.start({ prompt: 'js> ', eval: replEval }); } program .version(esper.version) .usage('[options] [script...]') .option('-v, --version', 'print esper version') .option('-i, --interactive', 'enter REPL') .option('-s, --strict', 'force strict mode') .option('-d, --debug', 'turn on performance debugging') .option('-c, --compile <mode>', 'set compileing mode') .option('-e, --eval <script>', 'evaluate script') .option('-p, --print <script>', 'evaluate script and print result') .option('-l, --language <language>', `set langauge (${Object.keys(esper.languages).join(', ')})`) .parse(process.argv); if ( program.language ) esper.plugin('lang-' + program.language); if ( program.v ) { console.log("v" + esper.version); process.exit(); } let engine = new Engine({ strict: !!program.strict, debug: !!program.debug, runtime: true, addInternalStack: !!program.debug, compile: program.compile || 'pre', language: program.language || 'javascript', esposeESHostGlobal: true, esRealms: true, }); let toEval = program.args.slice(0).map((f) => ({type: 'file', value: f})); if ( program.eval ) toEval.push({type: 'str', value: program.eval + '\n'}); if ( program.print ) toEval.push({type: 'str', value: program.print + '\n', print: true}); if ( toEval.length < 1 ) program.interactive = true; function next() { if ( toEval.length === 0 ) { if ( program.interactive ) return enterRepl(); else return process.exit(); } var fn = toEval.shift(); var code; if ( fn.type === 'file' ) { code = fs.readFileSync(fn.value, 'utf8'); } else { code = fn.value; } return engine.evalDetatched(code).then(function(val) { if ( fn.print && val ) console.log(val.debugString); return next(); }).catch(function(e) { if ( e.stack ) { process.stderr.write(e.stack + "\n"); } else { process.stderr.write(`${e.name}: ${e.message}\n`); } }); } next(); /* Usage: node [options] [ -e script | script.js ] [arguments] node debug script.js [arguments] Options: -v, --version print Node.js version -e, --eval script evaluate script -p, --print evaluate script and print result -c, --check syntax check script without executing -i, --interactive always enter the REPL even if stdin does not appear to be a terminal -r, --require module to preload (option can be repeated) --no-deprecation silence deprecation warnings --throw-deprecation throw an exception anytime a deprecated function is used --trace-deprecation show stack traces on deprecations --trace-sync-io show stack trace when use of sync IO is detected after the first tick --track-heap-objects track heap object allocations for heap snapshots --v8-options print v8 command line options --tls-cipher-list=val use an alternative default TLS cipher list --icu-data-dir=dir set ICU data load path to dir (overrides NODE_ICU_DATA) Environment variables: NODE_PATH ':'-separated list of directories prefixed to the module search path. NODE_DISABLE_COLORS set to 1 to disable colors in the REPL NODE_ICU_DATA data path for ICU (Intl object) data NODE_REPL_HISTORY path to the persistent REPL history file Documentation can be found at https://nodejs.org/ */
version https://git-lfs.github.com/spec/v1 oid sha256:8b2c75ae8236614319bbfe99cee3dba6fa2183434deff5a3dd2f69625589c74a size 391
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var rx_1 = require("rx"); /* tslint:enable */ function cache(callback) { var cached$ = this.replay(undefined, 1); var subscription = cached$.connect(); callback(function () { return subscription.dispose(); }); return cached$; } rx_1.Observable.prototype.cache = cache; //# sourceMappingURL=Rx.js.map
var chai = require('chai'); var should = chai.should(); var pictogramResponse = require('../../../lib/model/response/pictogramResponse'); describe('pictogramResponse model test', function () { var id = 'id'; var category = 'category'; var url = 'url'; it('should create model', function (done) { var pictogramResponseModel = new pictogramResponse.PictogramResponse( id, category, url ); should.exist(pictogramResponseModel); pictogramResponseModel.id.should.be.equal(id); pictogramResponseModel.category.should.be.equal(category); pictogramResponseModel.url.should.be.equal(url); done(); }); it('should create model by builder', function (done) { var pictogramResponseModel = new pictogramResponse.PictogramResponseBuilder() .withId(id) .withCategory(category) .withUrl(url) .build(); should.exist(pictogramResponseModel); pictogramResponseModel.id.should.be.equal(id); pictogramResponseModel.category.should.be.equal(category); pictogramResponseModel.url.should.be.equal(url); done(); }); });
import React from "react"; import { useResponse } from "@curi/react-dom"; import NavLinks from "./NavLinks"; export default function App() { let { response } = useResponse(); let { body: Body } = response; return ( <div> <NavLinks /> <Body response={response} /> </div> ); }
import { Tween } from '../core'; import { mat4 } from '../math'; export class MatrixTween extends Tween { action() { for (let i = 0; i < this.from.length; i++) { this.object[i] = this.from[i] + this.current_step * (this.to[i] - this.from[i]); } } pre_start() { super.pre_start(); this.from = mat4.clone(this.object); } }
import React from 'react'; import MobileTearSheet from './MobileTearSheet'; import List from 'material-ui/lib/lists/list'; import ListItem from 'material-ui/lib/lists/list-item'; import ActionInfo from 'material-ui/lib/svg-icons/action/info'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; import FileFolder from 'material-ui/lib/svg-icons/file/folder'; import ActionAssignment from 'material-ui/lib/svg-icons/action/assignment'; import Colors from 'material-ui/lib/styles/colors'; import EditorInsertChart from 'material-ui/lib/svg-icons/editor/insert-chart'; const ListExampleFolder = () => ( <MobileTearSheet> <List subheader="Folders" insetSubheader={true}> <ListItem leftAvatar={<Avatar icon={<FileFolder />} />} rightIcon={<ActionInfo />} primaryText="Photos" secondaryText="Jan 9, 2014" /> <ListItem leftAvatar={<Avatar icon={<FileFolder />} />} rightIcon={<ActionInfo />} primaryText="Recipes" secondaryText="Jan 17, 2014" /> <ListItem leftAvatar={<Avatar icon={<FileFolder />} />} rightIcon={<ActionInfo />} primaryText="Work" secondaryText="Jan 28, 2014" /> </List> <Divider inset={true} /> <List subheader="Files" insetSubheader={true}> <ListItem leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={Colors.blue500} />} rightIcon={<ActionInfo />} primaryText="Vacation itinerary" secondaryText="Jan 20, 2014" /> <ListItem leftAvatar={<Avatar icon={<EditorInsertChart />} backgroundColor={Colors.yellow600} />} rightIcon={<ActionInfo />} primaryText="Kitchen remodel" secondaryText="Jan 10, 2014" /> </List> </MobileTearSheet> ); export default ListExampleFolder;
module.exports = function Boot(game) { return { preload: function(){ game.load.image('mars', '/assets/images/mars.png'); }, create: function(){ //This is just like any other Phaser create function console.log('Boot was just loaded'); this.mars = game.add.sprite(0, 0, 'mars'); }, update: function(){ //Game logic goes here this.mars.x += 1; this.mars.y += 1; } } };
var topics = require('../data').topics; console.log(topics); var result = topics.filter(function (topic) { //filter renvoie les 'true' return topic.user.name === 'Leonard'; //? true : false; }); var result2 = topics.filter(topic=>topic.user.name === 'Leonard'); var titles = topics.map(function (topic) { return topic.title; }); var title2 = topics.map(topic=>topic.title); var hasViolence = topics.some(function (topic) { //renvoie true pour les topics avec violence return (topic.tags.includes('violence')); }); var hasViolence2 = topics.some(topic=>topic.tags.includes('violence')); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(result); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(result2); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(titles); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(title2); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log('hasViolence ', hasViolence); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var SheldonCom = topics.filter(function (topic) { return (topic.comments.some(function (comment) { return comment.user.name === 'Sheldon'; })); }).map(function (topic) { return (topic.title); }); var SheldonCom2; SheldonCom2 = topics.filter(topic=>topic.comments.some(comment=>comment.user.name === 'Sheldon')).map(topic=>topic.title); console.log('Sheldon has published in ', SheldonCom); console.log('Sheldon has published in ', SheldonCom2); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var idCommPenny = []; topics.forEach(function (topic) { topic.comments.forEach(function (comment) { if (comment.user.name === 'Penny') { idCommPenny.push(comment.id); } }) }); var sortFunction = (a, b) => a < b ? -1 : 1; idCommPenny.sort(sortFunction); console.log('Penny has post in : ', idCommPenny); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var Content = []; function getCommentByTag(tag, isAdmin) { topics.forEach(function (topic) { topic.comments.forEach(function (comment) { if (comment.tags !== undefined) { if (!comment.user.admin === isAdmin && comment.tags.includes(tag)) { Content.push(comment.content); } } }); }); return Content; }; console.log('Violent tag are present for these non-admin comments : ', getCommentByTag('fun', true)); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var searched = []; function search(term) { topics.forEach(function (topic) { topic.comments.forEach(function (comment) { if (comment.content.toLowerCase().includes(term.toLowerCase())) { searched.push(comment.content); } }) }); return searched; } console.log('search is present in :', search('it'));
StatsGopher.PresenceMonitor = function PresenceMonitor (opts) { opts = opts || {}; this.statsGopher = opts.statsGopher; this.key = opts.key; this.send = this.executeNextSend; this.paused = false; } StatsGopher.PresenceMonitor.prototype = { ignoreNextSend: function () { }, queueNextSend: function () { this.request.done(function () { this.send() }.bind(this)) this.send = this.ignoreNextSend }, executeNextSend: function () { var executeNextSend = function () { this.send = this.executeNextSend }.bind(this); if (this.paused) return; this.request = this.statsGopher.send({ code: this.code, key: this.key }).done(executeNextSend).fail(executeNextSend); this.send = this.queueNextSend }, pause: function () { this.paused = true }, resume: function () { this.paused = false } } StatsGopher.Heartbeat = function (opts) { StatsGopher.PresenceMonitor.apply(this, arguments) this.timeout = (typeof opts.timeout) === 'number' ? opts.timeout : 10000; } StatsGopher.Heartbeat.prototype = new StatsGopher.PresenceMonitor() StatsGopher.Heartbeat.prototype.code = 'heartbeat' StatsGopher.Heartbeat.prototype.start = function () { this.send() setTimeout(this.start.bind(this), 10000) } StatsGopher.UserActivity = function () { StatsGopher.PresenceMonitor.apply(this, arguments) } StatsGopher.UserActivity.prototype = new StatsGopher.PresenceMonitor() StatsGopher.UserActivity.prototype.code = 'user-activity' StatsGopher.UserActivity.prototype.listen = function () { var events = [ 'resize', 'click', 'mousedown', 'scroll', 'mousemove', 'keydown' ]; events.forEach(function (eventName) { window.addEventListener(eventName, function () { this.send(); }.bind(this)) }.bind(this)); }
app.service('operacoes', function() { this.somar = function(valor1, valor2) { return valor1 + valor2; } this.subtrair = function(valor1, valor2) { return valor1 - valor2; } });
function paddAppendClear() { jQuery('.append-clear').append('<div class="clear"></div>'); } function paddWrapInner1() { jQuery('.wrap-inner-1').wrapInner('<div class="inner"></div>'); } function paddWrapInner3() { jQuery('.wrap-inner-3').wrapInner('<div class="m"></div>'); jQuery('.wrap-inner-3').prepend('<div class="t"></div>'); jQuery('.wrap-inner-3').append('<div class="b"></div>'); } function paddToggle(classname,value) { jQuery(classname).focus(function() { if (value == jQuery(classname).val()) { jQuery(this).val(''); } }); jQuery(classname).blur(function() { if ('' == jQuery(classname).val()) { jQuery(this).val(value); } }); } jQuery(document).ready(function() { jQuery.noConflict(); jQuery('div#menubar div > ul').superfish({ hoverClass: 'hover', speed: 500, animation: { opacity: 'show', height: 'show' } }); paddAppendClear(); paddWrapInner1(); paddWrapInner3(); jQuery('p.older-articles').titleBoxShadow('#ebebeb'); jQuery('.hentry-large .title').titleBoxShadow('#ebebeb'); jQuery('.hentry-large .thumbnail img').imageBoxShadow('#ebebeb'); jQuery('input#s').val('Search this site'); paddToggle('input#s','Search this site'); jQuery('div.search form').click(function () { jQuery('input#s').focus(); }); });
(function () { 'use strict'; angular .module('patients') .controller('PatientsListController', PatientsListController); PatientsListController.$inject = ['PatientsService']; function PatientsListController(PatientsService) { var vm = this; vm.patients = PatientsService.query(); } })();
// Polyfills // (these modules are what are in 'angular2/bundles/angular2-polyfills' so don't use that here) // import 'ie-shim'; // Internet Explorer // import 'es6-shim'; // import 'es6-promise'; // import 'es7-reflect-metadata'; // Prefer CoreJS over the polyfills above require('core-js'); require('zone.js/dist/zone'); if ('production' === ENV) { } else { // Development Error.stackTraceLimit = Infinity; require('zone.js/dist/long-stack-trace-zone'); } //# sourceMappingURL=polyfills.js.map
'use strict'; //Setting up route angular.module('shop-list').config(['$stateProvider', function($stateProvider) { // Shop list state routing $stateProvider. state('detail-product', { url: '/detail-product/:productId', templateUrl: 'modules/shop-list/views/detail-product.client.view.html' }). state('products-list', { url: '/products-list', templateUrl: 'modules/shop-list/views/products-list.client.view.html' }); } ]);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; define(["require", "exports", "aurelia-framework", "./../../config"], function (require, exports, aurelia_framework_1, config_1) { "use strict"; var CardActionElement = (function () { function CardActionElement() { } CardActionElement.prototype.attached = function () { this.element.classList.add("card-action"); }; CardActionElement.prototype.detached = function () { this.element.classList.remove("card-action"); }; CardActionElement = __decorate([ aurelia_framework_1.customElement(config_1.config.cardAction), aurelia_framework_1.containerless(), aurelia_framework_1.inlineView("<template><div ref='element'><slot></slot></div></template>"), __metadata('design:paramtypes', []) ], CardActionElement); return CardActionElement; }()); exports.CardActionElement = CardActionElement; }); //# sourceMappingURL=cardActionElement.js.map
module.exports = function (grunt) { // Define the configuration for all the tasks grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Configure a mochaTest task mochaTest: { test: { options: { reporter: 'spec', ui: 'bdd', recursive: true, colors: true, 'check-leaks': true, growl: true, 'inline-diffs': true, 'no-exit': true, 'async-only': true }, src: ['test/**/*.js'] } } }); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('test', ['mochaTest']); };
import { createEllipsisItem, createFirstPage, createLastItem, createNextItem, createPageFactory, createPrevItem, } from 'src/lib/createPaginationItems/itemFactories' describe('itemFactories', () => { describe('createEllipsisItem', () => { it('"active" is always false', () => { createEllipsisItem(0).should.have.property('active', false) }) it('"type" matches "ellipsisItem"', () => { createEllipsisItem(0).should.have.property('type', 'ellipsisItem') }) it('"value" matches passed argument', () => { createEllipsisItem(5).should.have.property('value', 5) }) }) describe('createFirstPage', () => { it('"active" is always false', () => { createFirstPage().should.have.property('active', false) }) it('"type" matches "firstItem"', () => { createFirstPage().should.have.property('type', 'firstItem') }) it('"value" always returns 1', () => { createFirstPage().should.have.property('value', 1) }) }) describe('createPrevItem', () => { it('"active" is always false', () => { createPrevItem(1).should.have.property('active', false) }) it('"type" matches "prevItem"', () => { createPrevItem(1).should.have.property('type', 'prevItem') }) it('"value" returns previous page number or 1', () => { createPrevItem(1).should.have.property('value', 1) createPrevItem(2).should.have.property('value', 1) createPrevItem(3).should.have.property('value', 2) }) }) describe('createPageFactory', () => { const pageFactory = createPageFactory(1) it('returns function', () => { pageFactory.should.be.a('function') }) it('"active" is true when pageNumber is equal to activePage', () => { pageFactory(1).should.have.property('active', true) }) it('"active" is false when pageNumber is not equal to activePage', () => { pageFactory(2).should.have.property('active', false) }) it('"type" of created item matches "pageItem"', () => { pageFactory(2).should.have.property('type', 'pageItem') }) it('"value" returns pageNumber', () => { pageFactory(1).should.have.property('value', 1) pageFactory(2).should.have.property('value', 2) }) }) describe('createNextItem', () => { it('"active" is always false', () => { createNextItem(0, 0).should.have.property('active', false) }) it('"type" matches "nextItem"', () => { createNextItem(0, 0).should.have.property('type', 'nextItem') }) it('"value" returns the smallest of the arguments', () => { createNextItem(1, 3).should.have.property('value', 2) createNextItem(2, 3).should.have.property('value', 3) createNextItem(3, 3).should.have.property('value', 3) }) }) describe('createLastItem', () => { it('"active" is always false', () => { createLastItem(0).should.have.property('active', false) }) it('"type" matches "lastItem"', () => { createLastItem(0).should.have.property('type', 'lastItem') }) it('"value" matches passed argument', () => { createLastItem(2).should.have.property('value', 2) }) }) })
/** * App */ 'use strict'; // Base setup var express = require('express'); var app = express(); var path = require('path'); var bodyParser = require('body-parser'); var logger = require('morgan'); var mongoose = require('mongoose'); var config = require('./config'); var routes = require('./routes/index'); var validateRequest = require('./middlewares/validateRequest'); // Configuration mongoose.connect(config.db[app.get('env')], function(err) { if (err) { console.log('connection error', err); } else { console.log('connection successful'); } }); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // app.use(logger('dev')); // app.set('view engine', 'html'); // API Routes // app.all('/*', function(req, res, next) { // // CORS headers // res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain // res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); // // Set custom headers for CORS // res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key'); // if (req.method == 'OPTIONS') { // res.status(200).end(); // } else { // next(); // } // }); // Auth Middleware - This will check if the token is valid // Only the requests that start with /api/v1/* will be checked for the token. // Any URL's that do not follow the below pattern should be avoided unless you // are sure that authentication is not needed. app.all('/api/v1/*', [validateRequest]); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // Error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500).send(err.message); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500).send(err.message); }); module.exports = app;
$(document).ready(function(){ 'use strict'; //Turn off and on the music $("#sound-control").click(function() { var toggle = document.getElementById("sound-control"); var music = document.getElementById("music"); if(music.paused){ music.play(); $("#sound-control").attr('src', 'img/ljud_pa.png'); } else { music.pause(); $("#sound-control").attr('src', 'img/ljud_av.png'); } }); //The slideshow var started = false; //Backwards navigation $("#back").click(function() { stopSlideshow(); navigate("back"); }); //Forward navigation $("#next").click(function() { stopSlideshow(); navigate("next"); }); var interval; $("#control").click(function(){ if(started) { stopSlideshow(); } else { startSlideshow(); } }); var activeContainer = 1; var currentImg = 0; var animating = false; var navigate = function(direction) { //Check if no animation is running if(animating) { return; } //Check wich current image we need to show if(direction == "next") { currentImg++; if(currentImg == photos.length + 1) { currentImg = 1; } } else { currentImg--; if(currentImg == 0) { currentImg = photos.length; } } //Check wich container we need to use var currentContainer = activeContainer; if(activeContainer == 1) { activeContainer = 2; } else { activeContainer = 1; } showImage(photos[currentImg - 1], currentContainer, activeContainer); }; var currentZindex = -1; var showImage = function(photoObject, currentContainer, activeContainer) { animating = true; //Make sure the new container is always on the background currentZindex--; //Set the background image of the new active container $("#slideimg" + activeContainer).css({ "background-image" : "url(" + photoObject.image + ")", "display" : "block", "z-index" : currentZindex }); //Fade out and hide the slide-text when the new image is loading $("#slide-text").fadeOut(); $("#slide-text").css({"display" : "none"}); //Set the new header text $("#firstline").html(photoObject.firstline); $("#secondline") .attr("href", photoObject.url) .html(photoObject.secondline); //Fade out the current container //and display the slider-text when animation is complete $("#slideimg" + currentContainer).fadeOut(function() { setTimeout(function() { $("#slide-text").fadeIn(); animating = false; }, 500); }); }; var stopSlideshow = function() { //Change the background image to "play" $("#control").css({"background-image" : "url(img/play.png)" }); //Clear the interval clearInterval(interval); started = false; }; var startSlideshow = function() { $("#control").css({ "background-image" : "url(img/pause.png)" }); navigate("next"); interval = setInterval(function() { navigate("next"); }, slideshowSpeed); started = true; }; $.preloadImages = function() { $(photos).each(function() { $('<img>')[0].src = this.image; }); startSlideshow(); } $.preloadImages(); });
/* * Manifest Service * * Copyright (c) 2015 Thinknode Labs, LLC. All rights reserved. */ (function() { 'use strict'; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Service function loggerService() { /* jshint validthis: true */ this.logs = []; /** * @summary Appends a log message of a given type to the collection of logs. */ this.append = function(type, message) { this.logs.push({ "date": new Date(), "type": type, "message": message }); }; /** * @summary Clears the logs. */ this.clear = function() { this.logs.length = 0; }; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Register service angular.module('app').service('$logger', [loggerService]); })();
export { default } from './src/layout-container.vue';
/* *@author jaime P. Bravo */ $(document).ready(function () { //forms general function sendDataWithAjax(type, url, data) { return $.ajax({ type: type, url: url, data: data, dataType: 'json', beforeSend: function () { console.log('Enviando...'); }, success: function (response) { }, error: function (jqXHR, textStatus, errorThrown) { console.log('Código:' + jqXHR.status); console.log('Error AJAX: ' + textStatus); console.log('Tipo Error: ' + errorThrown); } }); } // Form create $('.create-form-view').submit(function (e) { e.preventDefault(); var url = $(this).attr('action'); var data = $(this).serialize(); var torre = sendDataWithAjax('POST', url, data); torre.success(function (response) { if (response.type === 'error') { generateNoty('bottomLeft', response.message, 'error'); } else { generateNoty('bottomLeft', response.message, 'success'); $('.form-group.input-type').removeClass('has-error'); $('.error-icon').hide(); resetForms('create-form-view'); if (response.login === 'si') { window.location.href = '/matters/index.php/inicio'; } } }); }); $('.dropdown.logo').click(function () { window.location.href = '/matters/index.php/inicio'; }); //Noty Master function function generateNoty(layout, text, type) { var n = noty({ text: text, type: type, dismissQueue: true, layout: layout, theme: 'relax', timeout: 4000 }); } //Datatables $('.table-datatable').DataTable({ "bStateSave": true }); }); //End jQuery function refreshTable(table) { $('.' + table + '').DataTable().ajax.reload(); } //Helper functions function resetForms(form_class) { $('.' + form_class + '').get(0).reset(); } //Hover submenus $(function () { $(".dropdown").hover( function () { $('.dropdown-menu', this).stop(true, true).fadeIn("fast"); $(this).toggleClass('open'); $('b', this).toggleClass("caret caret-up"); $('b', this).hover().toggleClass("caret caret-reversed"); }, function () { $('.dropdown-menu', this).stop(true, true).fadeOut("fast"); $(this).toggleClass('open'); $('b', this).toggleClass("caret caret-up"); $('b', this).hover().toggleClass("caret caret-reversed"); }); });
var LedgerRequestHandler = require('../../helpers/ledgerRequestHandler'); /** * @api {post} /gl/:LEDGER_ID/add-filter add filter * @apiGroup Ledger.Utils * @apiVersion v1.0.0 * * @apiDescription * Add a filter for caching balances. This will speed up balance * requests containing a matching filters. * * @apiParam {CounterpartyId[]} excludingCounterparties * IDs of transaction counterparties to exclude with the filter * @apiParam {AccountId[]} excludingContraAccounts * IDs of transaction countra accounts to exclude with the filter * @apiParam {CounterpartyId[]} [withCounterparties] * IDs of transaction counterparties to limit with the filter. All others will be * excluded. * * @apiParamExample {x-www-form-urlencoded} Request-Example: * excludingCounterparties=foobar-llc,foobar-inc * excludingContraAccounts=chase-saving,chase-checking * withCounterparties=staples,ubs */ module.exports = new LedgerRequestHandler({ validateBody: { 'excludingCounterparties': { type: 'string', required: true }, 'excludingContraAccounts': { type: 'string', required: true }, 'withCounterparties': { type: 'string' } }, commitLedger: true }).handle(function (options, cb) { var excludingCounterparties = options.body.excludingCounterparties.split(','); var excludingContraAccounts = options.body.excludingContraAccounts.split(','); var withCounterparties = options.body.withCounterparties && options.body.withCounterparties.split(','); var ledger = options.ledger; ledger.registerFilter({ excludingCounterparties: excludingCounterparties, excludingContraAccounts: excludingContraAccounts, withCounterparties: withCounterparties }); cb(null, ledger.toJson()); });
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 THE AUTHOR 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. */ 'use strict'; var _ = require('underscore'); var common = require('./common'); var groups = function(groups) { var buf = this.buf; buf.appendUInt32BE(groups.length); _.each(groups, function(group) { common.appendString(buf, group); }); return this; }; exports.encode = function(version) { var ret = common.encode(common.DESCRIBEGROUP_API, version); ret.groups = groups; return ret; };
// @flow /* ********************************************************** * File: Footer.js * * Brief: The react footer component * * Authors: Craig Cheney, George Whitfield * * 2017.04.27 CC - Document created * ********************************************************* */ import React, { Component } from 'react'; import { Grid, Col, Row } from 'react-bootstrap'; let mitImagePath = '../resources/img/mitLogo.png'; /* Set mitImagePath to new path */ if (process.resourcesPath !== undefined) { mitImagePath = (`${String(process.resourcesPath)}resources/img/mitLogo.png`); // mitImagePath = `${process.resourcesPath}resources/img/mitLogo.png`; } // const nativeImage = require('electron').nativeImage; // const mitLogoImage = nativeImage.createFromPath(mitImagePath); const footerStyle = { position: 'absolute', right: 0, bottom: 0, left: 0, color: '#9d9d9d', backgroundColor: '#222', height: '25px', textAlign: 'center' }; const mitLogoStyle = { height: '20px' }; const bilabLogoStyle = { height: '20px' }; export default class Footer extends Component<{}> { render() { return ( <Grid className='Footer' style={footerStyle} fluid> <Row> <Col xs={4}><img src={'../resources/img/mitLogo.png' || mitImagePath} style={mitLogoStyle} alt='MICA' /></Col> <Col xs={4}>The MICA Group &copy; 2017</Col> <Col xs={4}><img src='../resources/img/bilabLogo_white.png' style={bilabLogoStyle} alt='BioInstrumentation Lab' /></Col> </Row> </Grid> ); } } /* [] - END OF FILE */