text
stringlengths
2
6.14k
export const ATTR_ID = 'data-referid' export let info = { component: { amount: 0, mounts: 0, unmounts: 0 } } export let getId = () => Math.random().toString(36).substr(2) export let pipe = (fn1, fn2) => function(...args) { fn1.apply(this, args) return fn2.apply(this, args) } export let createCallbackStore = name => { let store = [] return { name, clear() { while (store.length) { store.shift()() } }, push(item) { store.push(item) }, store } } export let wrapNative = (obj, method, fn) => { let nativeMethod = obj[method] let wrapper = function(...args) { fn.apply(this, args) return nativeMethod.apply(this, args) } obj[method] = wrapper return () => obj[method] = nativeMethod } if (!Object.assign) { Object.assign = (target, ...args) => { args.forEach(source => { for (let key in source) { if (!source.hasOwnProperty(key)) { continue } target[key] = source[key] } }) return target } }
export default function _isEdge() { const ua = navigator.userAgent.toLowerCase(); return Boolean(ua.match(/edge/i)); }
const { QUERY_PROFILE_PROJECT, QUERY_PROFILE_ENVIRONMENT, QUERY_PROFILE_SETTINGS, MUTATION_LOG, MUTATION_SESSION, } = require('constants/permissions/values'); const { PRIVATE, } = require('constants/permissions/entries'); const app = require('./app'); const user = require('./user'); const { APP, USER } = require('constants/profiles/types'); const values = [ { value: QUERY_PROFILE_PROJECT, entries: [PRIVATE] }, { value: QUERY_PROFILE_ENVIRONMENT, entries: [PRIVATE] }, { value: QUERY_PROFILE_SETTINGS, entries: [PRIVATE] }, { value: MUTATION_LOG, entries: [PRIVATE] }, { value: MUTATION_SESSION, entries: [PRIVATE] }, ]; exports.values = values; exports[APP] = [...values, ...app]; exports[USER] = [...values, ...user];
(function() { 'use strict'; angular.module('facetApp') .directive('kblink', function() { return { restrict: 'EC', scope: { href: '@' }, transclude: true, controller: ['$scope', 'popoverService', function($scope, popoverService){ if (!$scope.href) return; $scope.image = false; $scope.lifespan = ''; popoverService.getHrefPopover($scope.href).then(function(data) { if (data.length) data = data[0]; $scope.label = data.label; $scope.link = '#!/henkilo/'+ (data.id).replace(/^.+?(p[0-9_]+)$/, '$1'); // check if lifespan contains any numbers if ((new RegExp(/\d/)).test(data.lifespan)) { // remove leading zeros (0800-0900) -> (800-900) data.lifespan = data.lifespan.replace(/(\D)0/g, "$1"); $scope.lifespan = data.lifespan; } if (data.hasOwnProperty('image')) $scope.image = data.image; }); }], template: '<a uib-popover-template="\'views/tooltips/personTooltipTemplate.html\'" popover-trigger="\'mouseenter\'" ng-href="{{ link }}" ng-transclude></a>' }}); })();
/* jshint node: true */ (function () { "use strict"; var APP; var utils = require("./utils"); var fs = require("fs"); var path = require("path"); var wrench = require("wrench"); var colors = require("colors"); var supervisor = require("supervisor"); function server(settingsFile, dir, port, interval) { utils.loadSettings(settingsFile, function (settings) { var i; dir = dir || path.join(path.dirname(settings.file), settings.source_dir); dir = dir.split(","); port = port || 8000; var reload = function (e, f) { restartServer(settings, port); }; for (i = 0; i < dir.length; i++) { fs.watch(dir[i], reload); } restartServer(settings, port); }); } function newProject(folder) { utils.fsCopy(path.join(path.dirname(__dirname), "example"), folder || "example"); } function restartServer(settings, port) { var rootDir = path.join(settings.source_dir), indexFound = false, express = require("express"), consolidate = require("consolidate"), app = express.createServer(); if (APP) { APP.close(); APP = null; } app.configure(function () { app.disable("view cache"); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(rootDir)); }); if (settings.expressConfig) { app.configure(settings.expressConfig(express, app)); } app.use(express.errorHandler({dumpExceptions: true, showStack: true})); function renderTemplate(page) { return function (req, res, next) { var prop, data = {layout : false}; for (prop in settings.global_data) { data[prop] = settings.global_data[prop]; } for (prop in page.data) { data[prop] = page.data[prop]; } consolidate[settings.template_engine](path.join(rootDir, page.source), data, function (err, html) { if (err) { throw err; } res.send(html); }); }; } var page, i, subdir; for (i = 0; i < settings.pages.length; i++) { page = settings.pages[i]; if (!indexFound && page.source.indexOf("index") > -1 || page.output.indexOf("index") > -1) { subdir = path.join(path.sep, page.output.substr(0, page.output.indexOf("index") - 1)); app.get(subdir, renderTemplate(page)); indexFound = true; } app.get(path.join(path.sep, page.output), renderTemplate(page)); } if (!indexFound) { app.get(path.sep, renderTemplate(settings.pages[0])); } var running = true; app.listen(port); console.log(""); app.on("error", function (e) { if (running) { running = false; if (e.code === "EADDRINUSE") { console.error(("Port " + port + " is already in use. Please try with a different port, or exit the process which is tying up the port.").yellow); } else { console.error(e); } } }); setTimeout(function () { if (running) { console.log("STATIX server is now running on port ".green + port.toString().yellow); } }, 500); APP = app; } function build(settingsFile) { utils.loadSettings(settingsFile, function (settings) { var consolidate = require("consolidate"), sourceDir = path.join(settings.source_dir), outputDir = path.join(settings.output_dir); console.log(""); settings.preBuild = settings.preBuild || function (cb) { return cb(); }; settings.preBuild(function () { if (fs.existsSync(outputDir)) { wrench.rmdirSyncRecursive(outputDir); } utils.copyMatchingFiles(sourceDir, outputDir, settings.include_patterns, settings.exclude_patterns); function renderTemplate(page, cb) { consolidate[settings.template_engine](path.join(sourceDir, page.source), data, function (err, html) { var outputFile = path.join(outputDir, page.output); if (fs.existsSync(outputFile)) { fs.unlinkSync(outputFile); } wrench.mkdirSyncRecursive(path.dirname(path.join(outputDir, page.output))); fs.writeFileSync(path.join(outputDir, page.output), html); if (cb) { cb(); } }); } function callback() { settings.postBuild = settings.postBuild || function (cb) { return cb(); }; settings.postBuild(function () { console.log("Statix build complete!".green); console.log(""); process.exit(); }); } for (var i = 0; i < settings.pages.length; i ++) { var page = settings.pages[i], data = {}, cb = null, prop; for (prop in settings.global_data) { data[prop] = settings.global_data[prop]; } for (prop in settings.build_data) { data[prop] = settings.build_data[prop]; } for (prop in page.data) { data[prop] = page.data[prop]; } if (i + 1 === settings.pages.length) { cb = callback; } renderTemplate(page, cb); } }); }); } module.exports = { utils : utils, server : server, newProject : newProject, restartServer : restartServer, build : build }; }());
Session.setDefault('isLoggingIn', false); Template.account.helpers({ signedUp: function() { return Package["brettle:accounts-login-state"].LoginState.signedUp() } }); Template.account.events({ 'click .logout': function(evt) { Meteor.logout(); evt.preventDefault(); }, 'click .login': function(evt) { Session.set('isLoggingIn', true); evt.preventDefault(); } });
var resource = require('../'), creature = resource.define('creature'); creature.persist('memory'); creature.property('name'); creature.before('create', function (data, next) { console.log('before creature.create') data.name += '-a'; next(null, data) }); creature.after('create', function (data, next) { console.log('after creature.create') data.name += "-b"; next(null, data); }); creature.create({ name: 'bobby' }, function (err, result) { console.log(err, result); }); creature.on('create', function(data){ console.log('create has been created!', data) }); creature.method('eat', function (options, callback){ callback(null, options); }); creature.on('eat', function(data){ console.log('create ate!', data) }); creature.eat({}, function(){}); creature.emit('eat', "food")
import { applyMiddleware, createStore, compose } from "redux"; //Connect react router with redux import { syncHistoryWithStore } from "react-router-redux"; import { browserHistory } from "react-router"; import logger from "redux-logger"; import thunk from "redux-thunk"; import promise from "redux-promise-middleware"; import rootReducer from './reducers/index.js'; // axsios //If making an initial state and passing as a preloadedState to createStore, need to make a reducer //for each property in the intial state. The reason being the reducer has access to the state. So //This is like setting the initial state for thee reducers here instead of doing it directly in the //reducer function itself. // const initialState = { // allData: 123, // sesssion // } const middleware = applyMiddleware(promise(), thunk, logger()); const store = createStore(rootReducer, middleware); export const history = syncHistoryWithStore(browserHistory, store); export default store;
var url = 'http://localhost:8313'; var kTickInterval = 5000; var kEmailRequired = false; window.onload = kRefreshState; var stateErrorDetails = { 'not ready': 'It looks like the "iGrabber Capture" application is not ' + 'running. Launch it from Applications > iGrabber Capture. (If it ' + 'is already running, try force quitting it and then launching it.)', 'stuck': 'The "iGrabber Capture" application is stuck. Try switching ' + 'to it and clicking the "OK" button.' }; function kRefreshState() { makeRequest('get', '/state', null, function () { setTimeout(kRefreshState, kTickInterval); }); } function kLoadState(data) { $('#kStatus').text(data); if (stateErrorDetails.hasOwnProperty(data)) { $('.kError').css('display', 'block'); $('.kError').text(stateErrorDetails[data]); } else { $('.kError').css('display', 'none'); } if (data == 'recording') { $('#kButtonStart').prop('value', 'Start recording another race'); $('#kButtonStart').prop('disabled', false); $('#kButtonStop').prop('disabled', false); } else if (data == 'idle') { $('#kButtonStart').prop('disabled', false); $('#kButtonStop').prop('disabled', 'true'); } else { $('#kButtonStart').prop('disabled', true); $('#kButtonStop').prop('disabled', true); } } function kLoadLog(elts) { var html = '<table class="kLog">' + elts.map(function (entry) { return ('<tr><td class="kLogWhen">' + new Date(entry[0]).toLocaleTimeString() + '</td><td class="kLogMessage">' + entry[1] + '</td></tr>'); }).join('\n') + '</table>'; $('#kLog').html(html); } function kReset() { $('input[type=text]').val(''); } function kStop() { makeRequest('post', '/stop', {}); } function kStart() { var obj, npl, msg; obj = {}; $('input[type=text]').each( function (_, e) { obj[e.id] = $(e).val(); }); npl = $('#np3')[0].checked ? 3 : 4; obj['nplayers'] = npl; obj['level'] = $('#50cc')[0].checked ? '50cc' : $('#100cc')[0].checked ? '100cc' : $('#150cc')[0].checked ? '150cc' : 'unknown'; if (!obj['p1handle'] || !obj['p2handle'] || !obj['p3handle'] || (npl == 4 && !obj['p4handle'])) msg = 'Handles are required. (Use "anon" for anonymous.)'; else if (kEmailRequired && (!obj['p1email'] || !obj['p2email'] || !obj['p3email'] || (npl == 4 && !obj['p4email']))) msg = 'Email address is required.'; if (msg) { alert(msg); return; } makeRequest('post', '/start', obj); } function makeRequest(method, path, args, callback) { var options = { 'url': url + path, 'method': method, 'dataType': 'json', 'success': function (data) { kLoadState(data['state']); kLoadLog(data['ulog']); if (callback) callback(); }, 'error': function (data) { var msg; try { msg = JSON.parse(data['responseText']); } catch (ex) {} if (msg && msg['message'].substr(0, 'bad state: '.length) == 'bad state: ') kLoadState(msg['message'].substr('bad state: '.length)); else console.error('failed request: ', path, data); if (callback) callback(new Error('failed')); } }; if (args) { options['contentType'] = 'application/json'; options['data'] = JSON.stringify(args); options['processData'] = false; } $.ajax(options); } function kNpChanged() { if ($('#np3')[0].checked) { $('#p4handle, #p4email').prop('disabled', true); $('#p4handle, #p4email').val(''); } else { $('#p4handle, #p4email').prop('disabled', false); } }
//require last.fm api client var LastFmNode = require('lastfm').LastFmNode; //get api keys from config file var config = require('../config.js'); //save.js to save json var save = require('../save.js'); // fs to open json var fs = require('fs'); //initialize api client var lastfm = new LastFmNode({ api_key: config.lastfm.key, // sign-up for a key at http://www.last.fm/api secret: config.lastfm.secret, useragent: 'api.lukemil.es' // optional. defaults to lastfm-node. }); // This job returns weekly last.fm play data. job('music-weekly', function(done) { //get user's weekly artist chart to do weekly play count var request = lastfm.request("user.getWeeklyArtistChart", { user: config.lastfm.username, handlers: { success: function(data) { //create object to later save var weeklySongs = new Object; weeklySongs.interval = 7; //eliminate unneeded data data = data.weeklyartistchart.artist; //get list of keys var artistkeys = Object.keys(data); // initialize plays variable weeklySongs.plays = 0; //initialize top artist variable weeklySongs.topArtist = new Object; // add number of unique artists to object weeklySongs.uniqueArtists = artistkeys.length; // iterate through keys for( var i = 0, length = artistkeys.length; i < length; i++ ) { //we have to do parseInt() because the JSON has the number as a string weeklySongs.plays = parseInt(data[artistkeys[ i ] ].playcount) + weeklySongs.plays; // save artist which is number 1 if (parseInt(data[artistkeys[i]]['@attr'].rank) === 1) { weeklySongs.topArtist.name = data[artistkeys[i]].name; weeklySongs.topArtist.count = parseInt(data[artistkeys[i]].playcount); } } save.file("music-weekly", weeklySongs); console.log('Weekly last.fm data updated.'); }, error: function(error) { return; } } }); }).every('1h'); // gets recent last fm data job('music-recent', function(done) { var request = lastfm.request("user.getRecentTracks", { user: config.lastfm.username, handlers: { success: function(data) { //create object to later save var recentSongs = new Object; // create object of just songs recentSongs.songs = []; recentSongs.interval = 1; //eliminate unneeded data recentSongs.nowPlaying = (data.recenttracks.track[0]["@attr"]) ? true : false; data = data.recenttracks.track; //iterate through artist data... //get list of keys var keys = Object.keys(data); // iterate through keys for(var i = 0, length = keys.length; i < length; i++) { //create temport object for song song = new Object; // create temporary object for working song from api lastSong = data[keys[i]]; //scoop up the data we want song.artist = lastSong.artist["#text"]; song.name = lastSong.name; song.album = lastSong.album["#text"]; song.image = lastSong.image[lastSong.image.length - 1]["#text"]; song.url = lastSong.url; // convert spaces to plusses and construct URL song.artistUrl = "http://www.last.fm/music/" + lastSong.artist["#text"].replace(/\s+/g, '+'); // cannot figure out why this line creates the error // [TypeError: Cannot read property '#time' of undefined] // it worked at first during my testing and stopped // song["time"] = lastSong["date"]["#time"]; // song.date_unix = lastSong["date"].uts //store data in main object recentSongs.songs[keys[i]] = song; } save.file("music-recent", recentSongs); console.log('Recent last.fm data updated.'); done(recentSongs); }, error: function(error) { console.log(error); return; } } }); }).every('90s'); job('music-combine', function(done, musicRecent) { // only combine file if music-weekly exists path = "json/music-weekly.json"; fs.exists(path, function(exists) { if (exists) { // synchronously open the weekly file var musicWeekly = JSON.parse(fs.readFileSync(path).toString()); // create new object to dump data in var music = new Object; // merge files into one object music.nowPlaying = musicRecent.nowPlaying; music.recent = musicRecent.songs; music.weeklyPlays = musicWeekly.plays; music.weeklyTopArtist = musicWeekly.topArtist; music.weeklyUniqueArtists = musicWeekly.uniqueArtists; // save to music.json console.log('music.json updated'); save.file("music", music); } }); }).after('music-recent');
import React from "react"; import { shallow } from "enzyme"; import { Link } from "react-router"; import { createMockUser } from "../../utilities/tests/test-utils"; import NavBar from "./NavBar"; const notLoggedUser = createMockUser(); const authenticatedUser = createMockUser("user@test.com", true, true, "ADMIN"); const authenticatedViewer = createMockUser("user@test.com", true, true, "VIEWER"); const defaultProps = { config: { enableDatasetImport: false, }, user: notLoggedUser, rootPath: "/florence", location: {}, }; const withPreviewNavProps = { ...defaultProps, location: { ...defaultProps.location, pathname: "/florence/collections/foo-1234/preview", }, workingOn: { id: "foo-1234", name: "foo", }, }; const NavbarItems = ["Collections", "Users and access", "Teams", "Security", "Sign out"]; describe("NavBar", () => { describe("when user is not authenticated", () => { it("should render only one link to Sign in", () => { const component = shallow(<NavBar {...defaultProps} />); expect(component.hasClass("global-nav__list")).toBe(true); expect(component.find(Link)).toHaveLength(1); expect(component.find("Link[to='/florence/login']").exists()).toBe(true); }); }); describe("when user is authenticated as Admin", () => { it("should render navigation with links", () => { const component = shallow(<NavBar {...defaultProps} user={authenticatedUser} />); const nav = component.find(Link); expect(component.hasClass("global-nav__list")).toBe(true); expect(component.find(Link)).toHaveLength(NavbarItems.length); nav.forEach((n, i) => expect(n.getElement().props.children).toBe(NavbarItems[i])); }); it("should not render Sign in link", () => { const component = shallow(<NavBar {...defaultProps} user={authenticatedUser} />); expect(component.hasClass("sign-in")).toBe(false); }); it("should not display Datasets", () => { const component = shallow(<NavBar {...defaultProps} user={authenticatedUser} />); expect(component.find("Link[to='/florence/uploads/data']").exists()).toBe(false); }); describe("when enableNewSignIn feature flag is enabled", () => { const props = { ...defaultProps, config: { ...defaultProps.config, enableNewSignIn: true, }, }; const component = shallow(<NavBar {...props} user={authenticatedUser} />); it("Preview teams option should be present", () => { const link = component.find("Link[to='/florence/groups']"); expect(link.getElement().props.children[0].includes("Preview teams")); }); }); describe("when enabled dataset import", () => { it("should display Datasets", () => { const props = { ...defaultProps, user: authenticatedUser, config: { ...defaultProps.config, enableDatasetImport: true, }, }; const component = shallow(<NavBar {...props} />); expect(component.find("Link[to='/florence/uploads/data']").exists()).toBe(true); }); }); describe("when enabled dataset import", () => { it("should display Datasets", () => { const props = { ...defaultProps, user: authenticatedUser, config: { ...defaultProps.config, enableDatasetImport: true, }, }; const component = shallow(<NavBar {...props} />); expect(component.find("Link[to='/florence/uploads/data']").exists()).toBe(true); }); }); describe("when on collections", () => { it("should display Working On: ", () => { const props = { ...defaultProps, user: authenticatedUser, location: { pathname: "/florence/collections/foo-1234", }, workingOn: { id: "foo-1234", name: "foo", }, }; const wrapper = shallow(<NavBar {...props} />); const link = wrapper.find("Link[to='/florence/collections/foo-1234']"); link.getElement().props.children[0].includes("Working on:"); link.getElement().props.children[0].includes("foo"); }); }); }); describe("when user is authenticated as Viewer", () => { it("should render navigation with links", () => { const NavbarItems = ["Collections", "Sign out"]; const component = shallow(<NavBar {...defaultProps} user={authenticatedViewer} />); const nav = component.find(Link); expect(component.hasClass("global-nav__list")).toBe(true); expect(component.find(Link)).toHaveLength(NavbarItems.length); nav.forEach((n, i) => expect(n.getElement().props.children).toBe(NavbarItems[i])); }); describe("when on collections url", () => { it("should render PreviewNav component", () => { const component = shallow(<NavBar {...withPreviewNavProps} user={authenticatedViewer} />); expect(component.find("Connect(PreviewNav)")).toHaveLength(1); }); }); }); });
'use strict'; module.exports = { db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/friend-around', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, 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' } };
/** * Presets of sentenceSeparator, clauseRegExp, wordRegExp, wordBoundaryRegExp, abbrRegExp * for each languages. */ export default { en: { sentenceSeparator: /\n/g, clauseRegExp: /[^,:"?!.]+/g, wordRegExp: /[\w'\-.]+(?!\s*\.\s*$)/g, wordBoundaryRegExp: /\b/, abbrRegExp: /\.\.\./g, }, ojp: { sentenceSeparator: /(?:。|[\n\r]+|「|」|『|』)(?:\s+)?/g, clauseRegExp: /[^、。「」『』]+/g, wordRegExp: /\S+/g, wordBoundaryRegExp: / /, abbrRegExp: /〜/g, }, };
'use strict'; describe("A suite", function() { it("contains spec with an expectation", function() { expect(true).toBe(true); }); });
/** * Created by sasha on 18.11.13. */
'use strict'; var BigNumber = require('bignumber.js'); var upperLimitMb = BigNumber(1024).times(16); var min = function(x, y) { return x.comparedTo(y) < 0 ? x : y }; var quotaMb = function(invites) { return min(BigNumber(2048).plus(BigNumber(512).times(invites)), upperLimitMb) }; module.exports = { cycles: { $subscription: { storageUsedMb: {}, invites: {} } }, values: { storageQuotaMb: function(invites) { return quotaMb(invites) } }, notifications: { storage10pcntLeft: function(storageUsedMb, storageQuotaMb) { return BigNumber(storageUsedMb).gt(BigNumber(storageQuotaMb).times(0.9)) }, storageOverUsed: function(storageUsedMb, storageQuotaMb) { return BigNumber(storageUsedMb).gt(storageQuotaMb) } } };
import React from 'react'; import { Router, Route, IndexRoute } from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import * as views from 'views'; import * as admin from 'views/admin'; import { RouteConstants } from 'constants'; const { HomeView, LayoutView } = views; const { AdminHomeView, AdminLayoutView } = admin; export default class App extends React.Component { constructor(props) { super(props); } render() { return ( <Router history={createBrowserHistory()}> <Route path='/' component={LayoutView}> <IndexRoute component={HomeView} /> <Route path={RouteConstants.ADMIN} component={AdminLayoutView}> <IndexRoute component={AdminHomeView} /> </Route> </Route> </Router> ); } }
import Image from 'next/image' import styles from '../styles/Home.module.scss' import About from '../components/About/About' import Header from '../components/Header/Header' import Photo from '../components/Photo/Photo' import { HomeContextProvider } from '../contexts/HomeContext/HomeContext' import Events from '../components/Events/Events' import Social from '../components/Social/Social' import casualImg from '../public/casual.jpeg' import scrumImg from '../public/scrum.jpeg' import presentationImg from '../public/presentation.jpg' import anniversaryImg from '../public/anniversary_cake.jpg' import bgImg from '../public/bg.jpg' export default function Home() { return ( <HomeContextProvider> <div className={styles.container}> <div className={styles.bg}> <Image src={bgImg} placeholder="blur" layout="fill" objectFit="cover" objectPosition="center" /> </div> <div className={styles.scrim} /> <Header /> <div className={styles.items}> <About /> <Photo src={casualImg} /> <Photo src={scrumImg} /> <Photo src={presentationImg} /> <Events /> <Photo src={anniversaryImg} /> </div> <Social /> </div> </HomeContextProvider> ) }
const SET_BLOGINFO = 'set/blog/info'; /* const SET_BLOGINFO_SUCCESS = 'set/blog/info/success'; const SET_BLOGINFO_FAIL = 'set/blog/info/fail'; */ const initialState = { data: require('../../db/jsonData/blogGroup.json').blogGroupBox }; export default function reducer(state = initialState, action = {}) { switch (action.type) { case SET_BLOGINFO: return { ...state, data: action.result }; default: return state; } }
'use strict'; // MODULES // var isNumber = require( 'validate.io-number-primitive' ), isArrayLike = require( 'validate.io-array-like' ), isTypedArrayLike = require( 'validate.io-typed-array-like' ), isMatrixLike = require( 'validate.io-matrix-like' ), ctors = require( 'compute-array-constructors' ), matrix = require( 'dstructs-matrix' ), validate = require( './validate.js' ); // FUNCTIONS // var pdf1 = require( './number.js' ), pdf2 = require( './array.js' ), pdf3 = require( './accessor.js' ), pdf4 = require( './deepset.js' ), pdf5 = require( './matrix.js' ), pdf6 = require( './typedarray.js' ); // PDF // /** * FUNCTION: pdf( x[, opts] ) * Evaluates the probability density function (PDF) for a Laplace distribution. * * @param {Number|Number[]|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Matrix} x - input value * @param {Object} [opts] - function options * @param {Number} [opts.mu=0] - location parameter * @param {Number} [opts.b=1] - scale parameter * @param {Boolean} [opts.copy=true] - boolean indicating if the function should return a new data structure * @param {Function} [opts.accessor] - accessor function for accessing array values * @param {String} [opts.path] - deep get/set key path * @param {String} [opts.sep="."] - deep get/set key path separator * @param {String} [opts.dtype="float64"] - output data type * @returns {Number|Number[]|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Matrix} evaluated PDF */ function pdf( x, options ) { /* jshint newcap:false */ var opts = {}, ctor, err, out, dt, d; if ( arguments.length > 1 ) { err = validate( opts, options ); if ( err ) { throw err; } } opts.mu = typeof opts.mu !== 'undefined' ? opts.mu : 0; opts.b = typeof opts.b !== 'undefined' ? opts.b : 1; if ( isNumber( x ) ) { return pdf1( x, opts.mu, opts.b ); } if ( isMatrixLike( x ) ) { if ( opts.copy !== false ) { dt = opts.dtype || 'float64'; ctor = ctors( dt ); if ( ctor === null ) { throw new Error( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' ); } // Create an output matrix: d = new ctor( x.length ); out = matrix( d, x.shape, dt ); } else { out = x; } return pdf5( out, x, opts.mu, opts.b ); } if ( isTypedArrayLike( x ) ) { if ( opts.copy === false ) { out = x; } else { dt = opts.dtype || 'float64'; ctor = ctors( dt ); if ( ctor === null ) { throw new Error( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' ); } out = new ctor( x.length ); } return pdf6( out, x, opts.mu, opts.b ); } if ( isArrayLike( x ) ) { // Handle deepset first... if ( opts.path ) { opts.sep = opts.sep || '.'; return pdf4( x, opts.mu, opts.b, opts.path, opts.sep ); } // Handle regular and accessor arrays next... if ( opts.copy === false ) { out = x; } else if ( opts.dtype ) { ctor = ctors( opts.dtype ); if ( ctor === null ) { throw new TypeError( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + opts.dtype + '`.' ); } out = new ctor( x.length ); } else { out = new Array( x.length ); } if ( opts.accessor ) { return pdf3( out, x, opts.mu, opts.b, opts.accessor ); } return pdf2( out, x, opts.mu, opts.b ); } return NaN; } // end FUNCTION pdf() // EXPORTS // module.exports = pdf;
'use strict'; module.exports = { port: 443, db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://root:root@ds125481.mlab.com:25481/clubs-manager', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-animate/angular-animate.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'https://localhost:443/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/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' } } } };
/* global _, angular */ 'use strict'; function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) { $scope.parentProfileData = ownProfile.data; $scope.tabs = []; function loadChildrenTabs () { $scope.tabs = []; cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, function (children) { $scope.children = _.sortBy(children, [ function (child) { return child.name.toLowerCase(); } ]); $scope.tabs = $scope.children.map(function (child) { return { state: 'my-children.child', stateParams: {id: child.userId}, tabImage: '/api/2.0/profiles/' + child.id + '/avatar_img', tabTitle: child.name, tabSubTitle: child.alias }; }); $scope.tabs.push({ state: 'my-children.add', tabImage: '/img/avatars/avatar.png', tabTitle: $translate.instant('Add Child') }); }); } loadChildrenTabs(); $scope.$on('$stateChangeStart', function (e, toState, params) { if (toState.name === 'my-children.child') { var childLoaded = _.some($scope.children, function (child) { return child.userId === params.id; }); if (!childLoaded) { loadChildrenTabs(); } } }); } angular.module('cpZenPlatform') .controller('my-children-controller', ['$scope', '$state', '$translate', 'ownProfile', 'cdUsersService', myChildrenCtrl]);
angular.module('app') .filter('date', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timestamp).format(format ? format : 'll') : '<date>'; }; }) .filter('datetime', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timestamp).format(format ? format : 'D MMM YYYY, HH:mm:ss') : '<datetime>'; }; }) .filter('time', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timestamp).format(format ? format : 'LT') : '<time>'; }; }) .filter('humanTime', function(){ 'use strict'; return function(timestamp){ return timestamp ? moment(timestamp).fromNow(true) : '<humanTime>'; }; }) .filter('duration', function(){ 'use strict'; return function(seconds, humanize){ if(seconds || seconds === 0){ if(humanize){ return moment.duration(seconds, 'seconds').humanize(); } else { var prefix = -60 < seconds && seconds < 60 ? '00:' : ''; return prefix + moment.duration(seconds, 'seconds').format('hh:mm:ss'); } } else { console.warn('Unable to format duration', seconds); return '<duration>'; } }; }) .filter('mynumber', function($filter){ 'use strict'; return function(number, round){ var mul = Math.pow(10, round ? round : 0); return $filter('number')(Math.round(number*mul)/mul); }; }) .filter('rating', function($filter){ 'use strict'; return function(rating, max, withText){ var stars = rating ? new Array(Math.floor(rating)+1).join('★') : ''; var maxStars = max ? new Array(Math.floor(max)-Math.floor(rating)+1).join('☆') : ''; var text = withText ? ' ('+$filter('mynumber')(rating, 1)+' / '+$filter('mynumber')(max, 1)+')' : ''; return stars+maxStars+text; }; });
import MPopper from '../m-popper.vue'; import pick from 'lodash/pick'; /** * 默认显示一个按钮,hover 上去有提示 */ export const UIconTooltip = { name: 'u-icon-tooltip', props: { type: { type: String, default: 'info' }, // 按钮名称 size: { type: String, default: 'normal' }, // 提示大小 content: String, trigger: { type: String, default: 'hover' }, placement: { type: String, default: 'bottom' }, ...pick(MPopper.props, [ 'opened', 'reference', 'hideDelay', 'boundariesElement', 'followCursor', 'offset', 'disabled', ]), }, }; export default UIconTooltip;
'use strict'; var path = require('path'), express = require('express'), errors = require('./errors'), debug = require('debug')('express-toybox:logger'), DEBUG = debug.enabled; /** * logger middleware using "morgan" or "debug". * * @param {*|String} options or log format. * @param {Number|Boolean} [options.buffer] * @param {Boolean} [options.immediate] * @param {Function} [options.skip] * @param {*} [options.stream] * @param {String} [options.format='combined'] log format. "combined", "common", "dev", "short", "tiny" or "default". * @param {String} [options.file] file to emit log. * @param {String} [options.debug] namespace for tj's debug namespace to emit log. * @returns {Function} connect/express middleware function */ function logger(options) { DEBUG && debug('configure http logger middleware', options); var format; if (typeof options === 'string') { format = options; options = {}; } else { format = options.format || 'combined'; delete options.format; } if (options.debug) { try { return require('morgan-debug')(options.debug, format, options); } catch (e) { console.error('**fatal** failed to configure logger with debug', e); return process.exit(2); } } if (options.file) { try { var file = path.resolve(process.cwd(), options.file); // replace stream options with stream object delete options.file; options.stream = require('fs').createWriteStream(file, {flags: 'a'}); } catch (e) { console.error('**fatal** failed to configure logger with file stream', e); return process.exit(2); } } console.warn('**fallback** use default logger middleware'); return require('morgan')(format, options); } module.exports = logger;
/* eslint-disable new-cap */ /* eslint-disable no-console */ const express = require('express'); const morgan = require('morgan'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const routes = require('./server/routes'); const config = require('./server/config'); const app = express(); const apiRouter = express.Router(); const env = process.env.NODE_ENV; if (env === 'test') { config.database = config.test_database; config.port = 8080; } app.use(morgan('dev')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/api', routes(apiRouter)); app.use((req, res, next) => { res.setHeader('Access-Coontrol-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type'); next(); }); mongoose.connect(config.database, (err) => { if (err) { console.log('connection error', err); } else { console.log('connection successful'); } }); app.listen(config.port, (err) => { if (err) { console.log('Connection error', err); } else { console.log('Listening on port:', config.port); } }); module.exports = app;
/* globals describe, it */ import Compiler from '../src/transpiler/compiler'; import assert from 'assert'; import fs from 'fs'; function compare(source, target) { const compiler = new Compiler(source); assert.equal(target, compiler.compiled); } describe('Transpiler', function() { it('should transpile a empty program', function() { compare('', ''); }); it('should transpile a declaration with no value', function() { compare('politico salario.,', 'var salario;'); }); it('should transpile a declaration with int value', function() { compare('politico salario = 100000.,', 'var salario = 100000;'); }); it('should transpile a declaration with string value', function() { compare('politico salario = \'salario\'.,', 'var salario = \'salario\';'); }); it('should transpile a declaration with boolean value', function() { compare('politico salario = true.,', 'var salario = true;'); compare('politico salario = false.,', 'var salario = false;'); }); it('should transpile a attribution of an expression', function() { compare('salario = salario + i.,', 'salario = salario + i;'); }); it('should transpile a print with no value', function() { compare('midiaGolpista().,', 'console.log();'); }); it('should transpile a print with string', function() { compare('midiaGolpista(\'Número abaixo de 100.000: \').,', 'console.log(\'Número abaixo de 100.000: \');'); }); it('should transpile a print with expression', function() { compare('midiaGolpista(\'Número abaixo de 100.000: \' + 1000).,', 'console.log(\'Número abaixo de 100.000: \' + 1000);'); }); it('should transpile a print with multiple values', function() { compare('midiaGolpista(\'Número abaixo de 100.000: \', 1000).,', 'console.log(\'Número abaixo de 100.000: \', 1000);'); }); it('should transpile a empty loop', function() { compare('euViVoceVeja (i = 0., i < 10000., i++) {}', 'for (i = 0; i < 10000; i++) {\n}'); }); it('should transpile a empty if', function() { compare('porque (salario < 100000) {}', 'if (salario < 100000) {\n}'); }); it('should transpile a empty if with empty else', function() { compare('porque (salario < 100000) {} casoContrario {}', 'if (salario < 100000) {\n}'); }); it('should transpile expression `1 + 1`', function() { compare('1 + 1', '1 + 1;'); }); it('should transpile expression `1 + 4 / 2`', function() { compare('1 + 4 / 2', '1 + 4 / 2;'); }); it('should transpile expression `4 / 2 + 1`', function() { compare('4 / 2 + 1', '4 / 2 + 1;'); }); it('should transpile expression `4 / 2 + 1 * 3 - 2`', function() { compare('4 / 2 + 1 * 3 - 2', '4 / 2 + 1 * 3 - 2;'); }); it('should transpile example 1', function() { const source = fs.readFileSync('Example - Loop.dilmalang').toString(); const target = fs.readFileSync('Example - Loop.js').toString().replace(/\n$/, ''); compare(source, target); }); });
/** * * @description Convert attribute value to boolean value * @param attribute * @return {Boolean} * @private */ jDoc.engines.OXML.prototype._attributeToBoolean = function (attribute) { return (!!attribute && (attribute.value == 'true' || attribute.value == '1' || attribute.value == 'on')); };
import Component from '@glimmer/component'; import {action} from '@ember/object'; export default class KoenigMenuContentComponent extends Component { @action scrollIntoView(element, [doScroll]) { if (doScroll) { element.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } } }
/** * Created by hbzhang on 8/7/15. */ 'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Widget = mongoose.model('Widget'), Upload = mongoose.model('Upload'), _ = require('lodash'), grid = require('gridfs-stream'); /** * Find widget by id */ exports.widget = function(req, res, next, id) { //console.log(id); Widget.load(id, function(err, widget) { if (err) return next(err); if (!widget) return next(new Error('Failed to load the widget' + id)); req.widget = widget; next(); }); }; exports.view = function(req, res) { //res.jsonp(req.class_); Widget.findOne({_id: req.param('widgetID') }, function (err, widget){ res.jsonp(widget); console.log(widget); }); }; /** * Create a widget */ exports.create = function(req, res) { //console.log(req.body); var widget = new Widget(req.body); //console.log(form); /* var e = dateValidation(class_); if (e !== '') { console.log(e); return res.jsonp(500, { error: e }); } */ widget.save(function(err) { if (err) { console.log(err); return res.jsonp(500, {error: 'cannot save the widget'}); } res.jsonp(widget); }); }; /** * List all widgets */ exports.all = function(req, res) { var populateQuery = [{path:'widgetcreator'}]; Widget.find({}, '_id widgetbasicinformation widgetformbuilder widgetroles').populate(populateQuery).exec(function(err, widgets) { if (err) { return res.jsonp(500, { error: 'Cannot list all the widgets' }); } res.jsonp(widgets); }); }; /** * Delete a widget */ exports.destroy = function(req, res) { //var event = req.event; //console.log(req.param('eventID')); Widget.remove({ _id: req.param('widgetID') }, function(err) { if (err) { return res.jsonp(500, { error: 'Cannot delete the widget' }); } res.jsonp({ _id: req.param('widgetID') }); }); }; /** * Update a widget */ exports.update = function(req, res) { Widget.findOne({_id: req.param('widgetID') }, function (err, widget){ widget.widgetbasicinformation = req.param('widgetbasicinformation'); widget.widgetformbuilder = req.param('widgetformbuilder'); widget.widgetcreator = req.param('widgetcreator'); widget.widgetroles = req.param('widgetroles'); widget.save(); res.jsonp(widget); }); };
const sensor = require('node-dht-sensor'); const logger = require('../logging/Logger'); /** * Reads pin 4 of the raspberry PI to obtain temperature and humidity information. * @return {Promise} A promise that will resolve with the results. In the * case where there was an error reading, will return a zero filled object, * with an additional error field. * { temperature: Number, * humidity: Number, * error: Error|undefined } */ exports.getHumidityTemperature = function() { return new Promise( (resolve, reject) => { sensor.read(22, 4, (err, temperature, humidity) => { if(err) { logger.error("Could not read from the DHT sensor. " + err); return resolve({ temperature: 0, humidity: 0, error: err}); } resolve({ temperature: temperature * 1.8 + 32, humidity: humidity}); }); }); }
var chartPrevious = [ {"Name":"", "Description":"charts"}, {"Name":"1 hour", "Description":"1 hour"}, {"Name":"2 hours", "Description":"2 hours"}, {"Name":"10 hours", "Description":"10 hours"}, {"Name":"1 day", "Description":"1 day"}, {"Name":"2 days", "Description":"2 days"}, {"Name":"3 days", "Description":"3 days"}, {"Name":"7 days", "Description":"7 days"}, {"Name":"14 days", "Description":"14 days"}, {"Name":"30 days", "Description":"30 days"} ]; var employees = [ {"name":"Employee10", "surname":"Employee1", "filename" : "sav3.png", "department":"marketing"}, {"name":"Employee11", "surname":"Employee1", "filename" : "who3.png", "department":"marketing"}, {"name":"Employee12", "surname":"Employee1", "filename" : "jac4.png", "department":"digital"}, {"name":"Employee13", "surname":"Employee1", "filename" : "mart4.png", "department":"digital"}, {"name":"Employee14", "surname":"Employee1", "filename" : "sav4.png", "department":"digital"}, {"name":"Employee15", "surname":"Employee1", "filename" : "who4.png", "department":"digital"}, {"name":"Employee16", "surname":"Employee1", "filename" : "jac5.png", "department":"digital"}, {"name":"Employee17", "surname":"Employee1", "filename" : "mart5.png", "department":"marketing"}, {"name":"Employee18", "surname":"Employee1", "filename" : "sav5.png", "department":"digital"}, {"name":"Employee19", "surname":"Employee1", "filename" : "who5.png", "department":"digital"}, {"name":"Employee1", "surname":"Employee1", "filename" : "jac1.png", "department":"marketing"}, {"name":"Employee2", "surname":"Employee1", "filename" : "mart1.png", "department":"marketing"}, {"name":"Employee3", "surname":"Employee1", "filename" : "sav1.png", "department":"marketing"}, {"name":"Employee4", "surname":"Employee1", "filename" : "who1.png", "department":"marketing"}, {"name":"Employee5", "surname":"Employee1", "filename" : "jac2.png", "department":"marketing"}, {"name":"Employee6", "surname":"Employee1", "filename" : "mart2.png", "department":"marketing"}, {"name":"Employee6", "surname":"Employee1", "filename" : "sav2.png", "department":"marketing"}, {"name":"Employee7", "surname":"Employee1", "filename" : "who2.png", "department":"marketing"}, {"name":"Employee8", "surname":"Employee1", "filename" : "jac3.png", "department":"marketing"}, {"name":"Employee9", "surname":"Employee1", "filename" : "mart3.png", "department":"marketing"}, {"name":"Employee20", "surname":"Employee1", "filename" : "jac6.png", "department":"marketing"}, {"name":"Employee21", "surname":"Employee1", "filename" : "mart6.png", "department":"marketing"}, {"name":"Employee22", "surname":"Employee1", "filename" : "sav6.png", "department":"marketing"}, {"name":"Employee23", "surname":"Employee1", "filename" : "who6.png", "department":"marketing"}, {"name":"Employee24", "surname":"Employee1", "filename" : "jac7.png", "department":"marketing"}, {"name":"Employee25", "surname":"Employee1", "filename" : "mart7.png", "department":"marketing"}, {"name":"Employee26", "surname":"Employee1", "filename" : "sav7.png", "department":"marketing"}, {"name":"Employee27", "surname":"Employee1", "filename" : "who7.png", "department":"marketing"}, {"name":"Employee28", "surname":"Employee1", "filename" : "jac8.png", "department":"staff"}, {"name":"Employee29", "surname":"Employee1", "filename" : "mart8.png", "department":"staff"}, {"name":"Employee40", "surname":"Employee1", "filename" : "jac11.png", "department":"staff"}, {"name":"Employee41", "surname":"Employee1", "filename" : "mart11.png", "department":"marketing"}, {"name":"Employee42", "surname":"Employee1", "filename" : "sav11.png", "department":"marketing"}, {"name":"Employee43", "surname":"Employee1", "filename" : "who11.png", "department":"marketing"}, {"name":"Employee44", "surname":"Employee1", "filename" : "jac12.png", "department":"staff"}, {"name":"Employee45", "surname":"Employee1", "filename" : "mart12.png", "department":"staff"}, {"name":"Employee46", "surname":"Employee1", "filename" : "sav12.png", "department":"staff"}, {"name":"Employee47", "surname":"Employee1", "filename" : "who12.png", "department":"staff"}, {"name":"Employee48", "surname":"Employee1", "filename" : "jac13.png", "department":"staff"}, {"name":"Employee49", "surname":"Employee1", "filename" : "mart13.png", "department":"staff"}, {"name":"Employee30", "surname":"Employee1", "filename" : "sav8.png", "department":"marketing"}, {"name":"Employee31", "surname":"Employee1", "filename" : "who8.png", "department":"marketing"}, {"name":"Employee32", "surname":"Employee1", "filename" : "jac9.png", "department":"marketing"}, {"name":"Employee33", "surname":"Employee1", "filename" : "mart9.png", "department":"staff"}, {"name":"Employee34", "surname":"Employee1", "filename" : "sav9.png", "department":"staff"}, {"name":"Employee35", "surname":"Employee1", "filename" : "who9.png", "department":"marketing"}, {"name":"Employee36", "surname":"Employee1", "filename" : "jac10.png", "department":"marketing"}, {"name":"Employee37", "surname":"Employee1", "filename" : "mart10.png", "department":"staff"}, {"name":"Employee38", "surname":"Employee1", "filename" : "sav10.png", "department":"staff"}, {"name":"Employee39", "surname":"Employee1", "filename" : "who10.png", "department":"staff"} ];
/*requires core.js*/ /*requires load.js*/ /*requires ajax.js*/ /*requires dom.js*/ /*requires selector.js*/ /*requires ua.js*/ /*requires event.js*/ /*requires ui.js*/ /*requires ui.tab.js*/ /*requires ui.slide.js*/ /*requires ui.nav.js*/ /** * nova.ui.flow * 在页面中四处飘浮的广告 * 遇到边界则改变飘浮方向 * @param number width element&img's width * @param number height element&img's height * @param string img's src * @param string anchor href */ nova.ui.flow = function() { var doc = document, html = doc.documentElement, body = doc.body, opt = arguments[0], xPos = 300, yPos = 200, step = 1, delay = 30, height = 0, Hoffset = 0, Woffset = 0, yon = 0, xon = 0, pause = true, interval; //生成广告元素 var elm = doc.createElement("div"); nova.dom.addClass(elm, "nova-ui-flow"); elm.innerHTML = '<a href="'+ opt.href + '"><img src="' + opt.src + '" width="' + opt.width + '" height="' + opt.height + '"></a>'; nova.dom.setCSS([elm], { position: "absolute", zIndex: "100", top: yPos + "px", left: "2px", width: opt.width + "px", height: opt.height + "px", visibility: "visible" }); body.appendChild(elm); var changePos = function () { width = body.clientWidth; height = html.clientHeight; Hoffset = elm.offsetHeight; Woffset = elm.offsetWidth; nova.dom.setCSS([elm], { left: xPos + doc.body.scrollLeft + "px", top: yPos + doc.body.scrollTop + "px" }); if (yon) { yPos = yPos + step; } else { yPos = yPos - step; } if (yPos < 0) { yon = 1; yPos = 0; } if (yPos >= (height - Hoffset)) { yon = 0; yPos = (height - Hoffset); } if (xon) { xPos = xPos + step; } else { xPos = xPos - step; } if (xPos < 0) { xon = 1; xPos = 0; } if (xPos >= (width - Woffset)) { xon = 0; xPos = (width - Woffset); } }; var pauseResume = function () { if (pause) { clearInterval(interval); pause = false; } else { interval = setInterval(changePos, delay); pause = true; } }; nova.Event.add(elm, "mouseover", pauseResume); nova.Event.add(elm, "mouseout", pauseResume); interval = setInterval(changePos, delay); };
version https://git-lfs.github.com/spec/v1 oid sha256:082a71326f3ffc5d4a12f1e2d1226bde6726d7e65fd21e9e633e1aa7bdd656d8 size 117145
define(['jquery', 'pubsub'], function($, pubsub) { function AudioPlayer(audio){ this.audio = audio; this._initSubscribe(); this.startPos = 0; this.endPos = 0; this.loopEnabled = false; } AudioPlayer.prototype._initSubscribe = function() { var self = this; $.subscribe("AudioCursor-clickedAudio", function(el, posCursor) { self.startPos = posCursor; self.audio.disableLoop(); }); $.subscribe("AudioCursor-selectedAudio", function(el, startPos, endPos) { self.startPos = startPos; self.endPos = endPos; self.audio.loop(startPos, endPos); }); $.subscribe("ToPlayer-play", function() { self.audio.play(self.startPos); }); $.subscribe("ToPlayer-pause", function() { self.startPos = null; self.audio.pause(); }); $.subscribe("Audio-end", function(){ self.startPos = null; }); $.subscribe("ToPlayer-stop", function() { self.startPos = null; self.audio.stop(); }); $.subscribe('ToAudioPlayer-disable', function(){ self.audio.disable(true); //true to not disable audio }); $.subscribe('ToAudioPlayer-enable', function(){ self.audio.enable(true); //true to not disable audio }); $.subscribe('ToPlayer-playPause', function() { if (self.audio.isPlaying){ $.publish('ToPlayer-pause'); } else { self.audio.play(self.startPos); } }); $.subscribe('ToPlayer-toggleLoop', function() { var toggle; if (self.loopEnabled){ toggle = self.audio.disableLoopSong(); }else{ toggle = self.audio.enableLoopSong(); } if (toggle){ self.loopEnabled = !self.loopEnabled; $.publish('PlayerModel-toggleLoop', self.loopEnabled); } }); }; return AudioPlayer; });
export class Schema { constructor(){ } createErrorMessage(schemaErrorObj, root){ let {errors, path} = schemaErrorObj; let pathName = path.replace('$root', root); let errorList = errors.reduce((errorListTemp, error, index)=>{ return `${errorListTemp} ${index+1}. ${error}` }, '') let errorMessage = ` Schema Error: Path: ${pathName} Errors: ${errorList} ` return errorMessage; } };
// Welcome. In this kata, you are asked to square every digit of a number. // // For example, if we run 9119 through the function, 811181 will come out. // // Note: The function accepts an integer and returns an integer function squareDigits(num){ let digits = (""+num).split(""); let arr=[]; for (var i = 0; i < digits.length; i++) { arr.push(Math.pow(digits[i],2)); } return +arr.join('') } //top codewars solution function squareDigits(num){ return Number(('' + num).split('').map(function (val) { return val * val;}).join('')); }
$(function() { $("#content").focus(function() { $(this).animate({"height": "85px",}, "fast" ); $("#button_block").slideDown("fast"); return false; }); $("#cancel").click(function() { $("#content").animate({"height": "30px",}, "fast" ); $("#button_block").slideUp("fast"); return false; }); function dragDrop(drag,i,j){ $(drag+i).draggable({ helper: 'clone', revert : function(event, ui) { // on older version of jQuery use "draggable" // $(this).data("draggable") // on 2.x versions of jQuery use "ui-draggable" // $(this).data("ui-draggable") $(this).data("uiDraggable").originalPosition = { top : 0, left : 0 }; // return boolean return !event; // that evaluate like this: // return event !== false ? false : true; } }); if(j==0){ $('#dropzone'+j).droppable({ tolerance: 'touch', activeClass: 'ui-state-default', hoverClass: 'ui-state-hover', drop: function(event, ui) { var id = ui.draggable.attr("id"); var res = id.substr(9,9); var post = parseInt(res); text = $('div#contenttext'+post).text(); // alert(id); $('#text').val(text); $.ajax({ type: "POST", url: "index.php", data: text, success:function(data){ $( ".tw-posts" ).prepend("<div class='tw-update'> <div class='post-container2'>"+text+"</div></div>"); $( "#button" ).trigger( "click" ); }, error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); //throw any errors } }); console.log(text); } }); } else { $('#dropzone'+j).droppable({ tolerance: 'touch', activeClass: 'ui-state-default', hoverClass: 'ui-state-hover'+j, drop: function(event, ui) { var id = ui.draggable.attr("id"); var res = id.substr(9,9); var post = parseInt(res); text = $('div#contenttext'+post).text(); // alert(id); $('#text').val(text); $.ajax({ type: "POST", url: "index.php", data: text, success:function(data){ $( ".tw-posts" ).prepend("<div class='tw-update'> <div class='post-container2'>"+text+"</div></div>"); $( "#button" ).trigger( "click" ); }, error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); //throw any errors } }); console.log(text); } }); } } for (i=0;i<10; i++) { dragDrop("#draggable",i,0); dragDrop("#draggabletw",i,1); } $('#publish').click( function(){ $.ajax({ type: "POST", url: "index.php", data: $("#form2").serialize(), // serializes the form's elements. beforeSend: function(){ }, success: function(data) { alert(data); // show response from the php script. } }); } ); /*$("#form2").submit(function() { var url = "publish.php"; // the script where you handle the form input. $.ajax({ type: "POST", url: url, data: $("#form2").serialize(), // serializes the form's elements. success: function(data) { alert(data); // show response from the php script. } }); return false; // avoid to execute the actual submit of the form. });*/ });
'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { $scope.authentication = Authentication; $(".signin").parent("section").css("height", "100%"); // If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/timeline'); $scope.signup = function() { $http.post('/auth/signup', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/signin'); }).error(function(response) { $scope.error = response.message; }); }; $scope.signin = function() { $http.post('/auth/signin', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/timeline'); }).error(function(response) { $scope.error = response.message; }); }; } ]);
(function(angular) { 'use strict'; //-----------------------------Controller Start------------------------------------ function AddBrandModalController($state, $http) { var ctrl = this; ctrl.init = function() { ctrl.brandDetail = (ctrl.resolve && ctrl.resolve.details) || {}; } ctrl.save = function(brand) { var data = { brandName: brand } $http({ url: "admin/addBrand", method: "POST", data: JSON.stringify(data), dataType: JSON }).then(function(response) { ctrl.modalInstance.close({ action: 'update'}); }) .catch(function(error) { console.log("Error while adding brand modal") }) } ctrl.cancel = function() { ctrl.modalInstance.close(); }; ctrl.init(); //------------------------------------Controller End------------------------------------ } angular.module('addBrandModalModule') .component('addBrandModalComponent', { templateUrl: 'admin/addBrand-modal/addBrand-modal.template.html', controller: ['$state', '$http', AddBrandModalController], bindings: { modalInstance: '<', resolve: '<' } }); })(window.angular);
$(function() { $('input:not(.button)').blur(function() { if (validation.isFieldValid(this.id, $(this).val())) { $('.error').text('').hide(); } else { $('.error').text(validation.form[this.id].errorMessage).show(); } }); });
'use strict'; /* Service to retrieve data from backend (CouchDB store) */ pissalotApp.factory('pissalotCouchService', function ($resource) { return $resource('http://192.168.1.4:8080/measurement/:listType',{ listType: '@listType' }, { get: { method: 'GET', isArray: false } }); });
const assert = require("assert"); describe("chain of iterators", function() { it("should conform to ES", function() { let finallyCalledSrc = 0; let finallyCalled1 = 0; let finallyCalled2 = 0; let cb; let p1 = new Promise(i => (cb = i)); let tasks = []; let cbtask; let p2 = { then(next) { tasks.push(next); cbtask(); } }; async function scheduler() { await new Promise(i => (cbtask = i)); tasks.pop()("t1"); } scheduler(); async function* src() { try { yield await p1; yield await p2; assert.fail("never"); } finally { finallyCalledSrc++; } } async function* a1() { try { for await (const i of src()) yield `a1:${i}`; assert.fail("never"); } finally { finallyCalled1 = true; } assert.fail("never"); } async function* a2() { try { yield* a1(); assert.fail("never"); } finally { finallyCalled2 = true; } } async function* a3() { const v = a2(); try { for (let i; !(i = await v.next()).done; ) { yield `a3:${i.value}`; } assert.fail("never"); } finally { await v.return(); } return 2; } async function a4() { const v = a3(); const i1 = await v.next(); assert.ok(!i1.done); assert.equal(i1.value, "a3:a1:hi"); const n = v.next(); const i2 = await n; assert.ok(!i2.done); assert.equal(i2.value, "a3:a1:t1"); const i3 = await v.return(4); assert.ok(i3.done); assert.equal(i3.value, 4); assert.ok(finallyCalledSrc); assert.ok(finallyCalled1); assert.ok(finallyCalled2); return 3; } const t4 = a4(); const res = t4.then(i => { assert.equal(i, 3); }); cb("hi"); return res; }); });
require("sdk/system/unload").when(function() { let prefService = require("sdk/preferences/service"); prefService.reset("general.useragent.site_specific_overrides"); prefService.reset("general.useragent.override.youtube.com"); prefService.reset("media.mediasource.enabled"); }); let prefService = require("sdk/preferences/service"); prefService.set('general.useragent.site_specific_overrides', true); prefService.set("general.useragent.override.youtube.com", "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36" ); prefService.set("media.mediasource.enabled", true);
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users.server.controller'); var orders = require('../../app/controllers/orders.server.controller'); // Orders Routes app.route('/orders') .get(orders.list) .post(users.requiresLogin, orders.create); app.route('/orders-analytics') .get(orders.analytics) app.route('/orders/:orderId') .get(orders.read) .put(users.requiresLogin, orders.hasAuthorization, orders.update) .delete(users.requiresLogin, orders.hasAuthorization, orders.delete); // Finish by binding the Order middleware app.param('orderId', orders.orderByID); };
// 2016-08-22 // // This is the wrapper for the native side /* prelim: start a server from the lib dir: python -m SimpleHTTPServer (python 2.x) (linux) python -m http.server (python 3.x) (windows) 1a) load jquery (note: may need a real active file open for this to work) Note: get message 'VM148:52 Uncaught (in promise) TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.(…)' if a real file is not open and active, when loading the second file. Note: refer to yaml libray as 'jsyaml' e.g. 'jsyaml.load()' fetch('http://code.jquery.com/jquery-latest.min.js').then(r => r.text()).then(r => {eval(r); eval(r);}); 1b) make sure you're editing a real file. test: make sure: document.getElementById('workbench.editors.files.textFileEditor') 1c) load all the other files Note: you'll get this message if not in a split-panel 'editor-theme-change-listener.js:39 Uncaught (in promise) TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'' document.MTA_VS = {}; $.when( fetch('http://localhost:8000/editor-theme-change-listener.js').then(r => r.text()).then(r => eval(r)), fetch('http://localhost:8000/local-theme-manager-native.js').then(r => r.text()).then(r => eval(r)), fetch('http://localhost:8000/mta-vs-native.js').then(r => r.text()).then(r => eval(r)) ) .done(function(first_call, second_call, third_call){ console.log('all loaded'); }) .fail(function(){ console.log('load failed'); }); // Note: server now automatically starts when your run 'mta-vs' 3) // then do a word setup so a "Theme:" appears in the status line 4) then change the theme with 'mta-vs' */ fetch('http://localhost:8000/cmd-channel-listener-native.js') .then(r => r.text()) .then(r => eval(r)) .then(() => { console.log('mta-vs-naitve: Now in final then for cmd-channel-listener setup.') var cmdChannelListenerNative = new document.CmdChannelListenerNative(); cmdChannelListenerNative.observe(); }); //@ sourceURL=mta-vs-native.js
(function(){ function newThreadCtrl($location, $state, MessageEditorService){ var vm = this; vm.getConstants = function(){ return MessageEditorService.pmConstants; }; vm.newThread = MessageEditorService.getThreadTemplate($location.search().boardId); vm.returnToBoard = function(){ var boardId = $location.search().boardId; $state.go('board',{boardId: boardId}); }; vm.previewThread = function(){ vm.previewThread = MessageEditorService.getThreadPreview(vm.newThread); vm.previewThread.$promise.then(function(data){ vm.preview = true; }); }; vm.postThread = function(){ MessageEditorService.saveThread(vm.newThread).$promise.then(function(data){ }); } vm.isOpen = false; } angular.module('zfgc.forum') .controller('newThreadCtrl', ['$location', '$state', 'MessageEditorService', newThreadCtrl]); })();
angular.module('starter.controllers', []) // A simple controller that fetches a list of data from a service .controller('JobIndexCtrl', function($rootScope, PetService) { // "Pets" is a service returning mock data (services.js) $rootScope.pets = PetService.all(); }) // A simple controller that shows a tapped item's data .controller('PetDetailCtrl', function($scope, $rootScope, $state, $stateParams, PetService) { $rootScope.pet = PetService.get($stateParams.jobId); $scope.goBack = $state.go('job.pet-index'); }) .controller('NewJobDetailCtrl', function($scope, $rootScope, $state, $stateParams, PetService) { $rootScope.pet = PetService.get($stateParams.jobId); $scope.goBack = $state.go('new-job'); }) .controller('LoginCtrl', function($scope, $state) { $scope.login = function () { $state.go("tab.adopt"); }; }) .controller('JobCreationCtrl', function($scope, $rootScope, $state, $stateParams, $localstorage, PetService) { $scope.createJob = function () { var title = document.getElementById("title"); var desc = document.getElementById("desc"); var location = document.getElementById("location"); if (title.value.trim() !== "" && desc.value.trim() !== "" && location.value.trim() !== "") { var newJobId = $localstorage.length() - 1; var newJob = { id: String(newJobId), title: String(title.value.trim()), description: String(desc.value.trim()), location: String(location.value.trim()), quote: { damageDesc: "", estimatedCost: "", estimatedTime: "", }, report: { fixDesc: "", actualCost: "", startTime: "", finishTime: "" } }; $rootScope.pet = PetService.get(newJobId); $rootScope.pets = PetService.all(); $localstorage.setObject(newJobId, newJob); $state.go('new-quote', {'jobId' : newJobId}); } } });
goog.provide('glift.displays.commentbox'); glift.displays.commentbox = {};
/**YEngine2D * author:YYC * date:2014-04-21 * email:395976266@qq.com * qq: 395976266 * blog:http://www.cnblogs.com/chaogex/ */ describe("CallFunc", function () { var action = null; var sandbox = null; beforeEach(function () { sandbox = sinon.sandbox.create(); action = new YE.CallFunc(); }); afterEach(function () { }); describe("init", function () { it("获得方法上下文、方法、传入方法的参数数组", function () { }); }); describe("update", function () { // it("如果方法为空,则直接完成动作", function () { // sandbox.stub(action, "finish"); // // action.update(); // // expect(action.finish).toCalledOnce(); // }); // describe("否则", function () { var context = null, func = null, data = null, target = null; function setParam(func, context, dataArr) { action.ye___context = context; action.ye___callFunc = func; action.ye___dataArr = dataArr; } beforeEach(function () { context = {}; func = sandbox.createSpyObj("call"); data = 1; target = {a: 1}; setParam(func, context, [data]); sandbox.stub(action, "getTarget").returns(target); }); it("调用方法,设置其上下文为context,并传入target和参数数组", function () { action.update(); expect(func.call).toCalledWith(context, target, [data]); }); it("完成动作", function () { sandbox.stub(action, "finish"); action.update(); expect(action.finish).toCalledOnce(); }); // }); }); describe("copy", function () { it("返回动作副本", function () { var a = action.copy(); expect(a).toBeInstanceOf(YE.CallFunc); expect(a === action).toBeFalsy(); }); it("传入的参数要进行深拷贝", function () { var data = {a: 1}; action.ye___dataArr = [data]; var a = action.copy(); a.ye___dataArr[0].a = 100; expect(data.a).toEqual(1); }); }); describe("reverse", function () { it("直接返回动作", function () { expect(action.reverse()).toBeSame(action); }); }); // describe("isFinish", function () { // it("返回true", function () { // expect(action.isFinish()).toBeTruthy(); // }); // }); describe("create", function () { it("创建实例并返回", function () { expect(YE.CallFunc.create()).toBeInstanceOf(YE.CallFunc); }); }); });
/////////////////////////////////////////////////////////////////////////// // Copyright © 2014 - 2016 Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define([ 'dojo/_base/declare', 'jimu/BaseFeatureAction', 'jimu/WidgetManager' ], function(declare, BaseFeatureAction, WidgetManager) { var clazz = declare(BaseFeatureAction, { iconClass: 'icon-direction-to', isFeatureSupported: function(featureSet) { return featureSet.features.length === 1 && featureSet.geometryType === "point"; }, onExecute: function(featureSet) { WidgetManager.getInstance().triggerWidgetOpen(this.widgetId).then(function(directionWidget) { if (featureSet.features.length === 1 && featureSet.geometryType === "point") { if (featureSet.features[0].geometry && featureSet.features[0].geometry.type === "point") { directionWidget.addStop(featureSet.features[0].geometry); } } }); } }); return clazz; });
module.exports = { path: { scripts: '/assets/scripts', styles: '/assets/styles', images: '/assets/images' }, site: { url: require('./package.json').mylly.url, name: 'My website', lang: 'en', charset: 'utf-8', ua: '' // UA-XXXXXX-XX }, page: {} };
/* eslint-env mocha */ 'use strict' const path = require('path') const cwd = process.cwd() const NetSuite = require(path.join(cwd, 'netsuite')) const chai = require('chai') const expect = chai.expect const config = require('config') describe('NetSuite class', function () { this.timeout(24 * 60 * 60 * 1000) it('should export a function', function () { expect(NetSuite).to.be.a('function') expect(new NetSuite({})).to.be.a('object') }) it('should search and searchMoreWithId', async function () { let ns = new NetSuite(opts()) let result = await ns.search({type: 'FolderSearch'}) expect(result.searchResult).to.be.a('object') expect(result.searchResult.status).to.be.a('object') expect(result.searchResult.status.attributes).to.be.a('object') expect(result.searchResult.status.attributes.isSuccess).to.equal('true') expect(result.searchResult.pageIndex).to.equal(1) let more = await ns.searchMoreWithId(result) expect(more.searchResult).to.be.a('object') expect(more.searchResult.pageIndex).to.equal(2) }) it('should search folders', async function () { let ns = new NetSuite(opts()) let result = await ns.search({type: 'FolderSearch'}) expect(result.searchResult.status.attributes.isSuccess).to.equal('true') }) it('should search files', async function () { let ns = new NetSuite(opts()) let result = await ns.search({type: 'FileSearch'}) expect(result.searchResult.status.attributes.isSuccess).to.equal('true') }) it('should get files', async function () { let ns = new NetSuite(opts()) let internalId = '88' let result = await ns.get({type: 'file', internalId: internalId}) expect(result.readResponse).to.be.a('object') expect(result.readResponse.status).to.be.a('object') expect(result.readResponse.status.attributes).to.be.a('object') expect(result.readResponse.status.attributes.isSuccess).to.equal('true') expect(result.readResponse.record.attributes.internalId).to.equal(internalId) }) }) const opts = () => { return { appId: config.get('appId'), passport: {account: config.get('account'), email: config.get('email'), password: config.get('password')}, searchPrefs: {bodyFieldsOnly: false, pageSize: 10}, debug: false } }
/** * version: 1.1.10 */ angular.module('ngWig', ['ngwig-app-templates']); angular.module('ngWig') .directive('ngWig', function () { return { scope: { content: '=ngWig' }, restrict: 'A', replace: true, templateUrl: 'ng-wig/views/ng-wig.html', link: function (scope, element, attrs) { scope.editMode = false; scope.autoexpand = !('autoexpand' in attrs) || attrs['autoexpand'] !== 'off'; scope.toggleEditMode = function () { scope.editMode = !scope.editMode; }; scope.execCommand = function (command, options) { if (command === 'createlink') { options = prompt('Please enter the URL', 'http://'); } if (command === 'insertimage') { options = prompt('Please enter an image URL to insert', 'http://'); } if (options !== null) { scope.$emit('execCommand', {command: command, options: options}); } }; scope.styles = [ {name: 'Normal text', value: 'p'}, {name: 'Header 1', value: 'h1'}, {name: 'Header 2', value: 'h2'}, {name: 'Header 3', value: 'h3'} ]; scope.style = scope.styles[0]; scope.$on("colorpicker-selected", function ($event, color) { scope.execCommand('foreColor', color.value); }); } } }); angular.module('ngWig') .directive('ngWigEditable', function () { function init(scope, $element, attrs, ctrl) { var document = $element[0].ownerDocument; $element.attr('contenteditable', true); //model --> view ctrl.$render = function () { $element.html(ctrl.$viewValue || ''); }; //view --> model function viewToModel() { ctrl.$setViewValue($element.html()); //to support Angular 1.2.x if (angular.version.minor < 3) { scope.$apply(); } } $element.bind('blur keyup change paste', viewToModel); scope.$on('execCommand', function (event, params) { $element[0].focus(); var ieStyleTextSelection = document.selection, command = params.command, options = params.options; if (ieStyleTextSelection) { var textRange = ieStyleTextSelection.createRange(); } document.execCommand(command, false, options); if (ieStyleTextSelection) { textRange.collapse(false); textRange.select(); } viewToModel(); }); } return { restrict: 'A', require: 'ngModel', replace: true, link: init } } ); angular.module('ngwig-app-templates', ['ng-wig/views/ng-wig.html']); angular.module("ng-wig/views/ng-wig.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("ng-wig/views/ng-wig.html", "<div class=\"ng-wig\">\n" + " <ul class=\"nw-toolbar\">\n" + " <li class=\"nw-toolbar__item\">\n" + " <select class=\"nw-select\" ng-model=\"style\" ng-change=\"execCommand('formatblock', style.value)\" ng-options=\"style.name for style in styles\">\n" + " </select>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--unordered-list\" title=\"Unordered List\" ng-click=\"execCommand('insertunorderedlist')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--ordered-list\" title=\"Ordered List\" ng-click=\"execCommand('insertorderedlist')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--bold\" title=\"Bold\" ng-click=\"execCommand('bold')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--italic\" title=\"Italic\" ng-click=\"execCommand('italic')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button colorpicker ng-model=\"fontcolor\" class=\"nw-button nw-button--text-color\" title=\"Font Color\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--link\" title=\"link\" ng-click=\"execCommand('createlink')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--image\" title=\"image\" ng-click=\"execCommand('insertimage')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--source\" ng-class=\"{ 'nw-button--active': editMode }\" ng-click=\"toggleEditMode()\"></button>\n" + " </li>\n" + " </ul>\n" + "\n" + " <div class=\"nw-editor-container\">\n" + " <div class=\"nw-editor\">\n" + " <textarea class=\"nw-editor__src\" ng-show=\"editMode\" ng-model=\"content\"></textarea>\n" + " <div ng-class=\"{'nw-invisible': editMode, 'nw-autoexpand': autoexpand}\" class=\"nw-editor__res\" ng-model=\"content\" ng-wig-editable></div>\n" + " </div>\n" + " </div>\n" + "</div>\n" + ""); }]);
/** * main.js: The entry point for MuTube. * Plays the role of the 'main process' in Electron. */ // define constants from various packages for the main process const { app, BrowserWindow, ipcMain } = require('electron'); let mainWindow; // execute the application app.on('ready', () => { // create the main broswer window with the following array values mainWindow = new BrowserWindow({ title: "MuTube", width: 600, height: 600, minWidth: 600, minHeight: 600, center: true, backgroundColor: "#181818", // mainly for Linux-based OSes running GTK darkTheme: true, // only for macOS when scrolling passed the beginning and ends of page scrollBounce: true }); // remove the menu bar mainWindow.setMenu(null); // load broswer window content mainWindow.loadURL('file://' + __dirname + '/html/index.html'); }); // when ipc receives signal, 'toggleDevTools', from renderer ipcMain.on('toggleDevTools', function() { if (mainWindow.isDevToolsOpened()) { mainWindow.closeDevTools(); } else { mainWindow.openDevTools({ mode: 'detach' }); } });
/*global Backbone */ var Generator = Generator || {}; (function () { 'use strict'; // Aspect Model // ---------- Generator.Aspect = Backbone.Model.extend({ defaults: { result: 0, text: '' } }); })();
version https://git-lfs.github.com/spec/v1 oid sha256:4fc049501415815d5fa555bc735c359c381441d2107851b32b30ae5ba192a892 size 11548
function Loader() { var self = this; self.cache = {}; // Filename -> {Geometry, Material, [callbacks]} self.textureCache = {}; // Filename -> Texture self.loader = new THREE.JSONLoader(); } Loader.prototype.loadTexture = function(filename, callback) { var self = this; var texture = self.textureCache[filename]; if(texture === undefined) { texture = THREE.ImageUtils.loadTexture(filename, undefined, callback); self.textureCache[filename] = texture; } return texture; }; Loader.prototype.loadTextureCube = function(filenames, callback) { var self = this; var filename = filenames[0]; // Use the first texture as the lookup name var texture = self.textureCache[filename]; if(texture === undefined) { texture = THREE.ImageUtils.loadTextureCube(filenames, undefined, callback); self.textureCache[filename] = texture; } else { callback(texture); } }; Loader.prototype.loadMesh = function(filename, callback) { var self = this; // Don't worry about texture caching because ThreeJS caches all loaded images // and material.clone creates shallow copies of textures. var cacheData = self.cache[filename]; if(cacheData === undefined) { // Not found in cache, load now // Add initial entry to cache var cacheData = { loaded: false, geometry: null, material: null, callbacks: [] }; self.cache[filename] = cacheData; // Load the json file self.loader.load(filename, function(geometry, materials) { // Finished loading // Update the cache var material = self.createMaterial(materials); cacheData.geometry = geometry; cacheData.material = material; cacheData.loaded = true; // Call the callback on this callback(geometry, self.cloneMaterial(material)); // Call the callbacks for all other objects created before this finished loading for(var i = 0; i < cacheData.callbacks.length; i++) { var callbackCached = cacheData.callbacks[i]; callbackCached(geometry, self.cloneMaterial(material)); } }); } else { // Check if the cache data is loaded. If not add the callback if(cacheData.loaded) { var geometry = cacheData.geometry; var material = self.cloneMaterial(cacheData.material); callback(geometry, material); } else { cacheData.callbacks.push(callback); } } }; Loader.prototype.createMaterial = function(materials) { var meshMaterial; if(materials === undefined){ meshMaterial = new THREE.MeshLambertMaterial(); materials = [meshMaterial]; } else if(materials.length == 1) meshMaterial = materials[0]; else meshMaterial = new THREE.MeshFaceMaterial(materials); // Fix materials for(var i = 0; i < materials.length; i++) { var material = materials[i]; if(material.map) { material.map.wrapS = material.map.wrapT = THREE.RepeatWrapping; // Set repeat wrapping //if(material.transparent) material.opacity = 1.0; // If transparent and it has a texture, set opacity to 1.0 } if(material.transparent) { material.depthWrite = false; //material.side = THREE.DoubleSide; material.side = THREE.FrontSide; } else { material.side = THREE.FrontSide; } // For editor purposes material.transparentOld = material.transparent; material.opacityOld = material.opacity; } return meshMaterial; }; Loader.prototype.cloneMaterial = function(material) { var newMaterial = material.clone(); newMaterial.transparentOld = material.transparentOld; newMaterial.opacityOld = material.opacityOld; return newMaterial; }; Loader.prototype.dispose = function() { // Not really necessary to call this function since the memory will be reused elsewhere var self = this; // Dispose geometries var geometryKeys = Object.keys(self.geometryCache); for(var i = 0; i < geometryKeys.length; i++) { var key = geometryKeys[i]; var geometry = self.geometryCache[key]; geometry.dispose(); } self.geometryCache = {}; // Dispose materials // No listeners are attached in the ThreeJS source, so this doesn't do anything var materialKeys = Object.keys(self.materialCache); for(var i = 0; i < materialKeys.length; i++) { var key = materialKeys[i]; var material = self.matericalCache[key]; var materials = Util.getMaterials(material); // Get all the materials in the material (e.g. MeshFaceMaterial) for(var j = 0; j < materials.length; j++) { var material = materials[j]; material.dispose(); } } self.materialCache = {}; // TO-DO: Dispose textures. // Find all the textures on all the materials // or go directly to WebGLTextures.js and manually delete there };
import header from 'head'; class Loader { constructor () { // Singleton Object if(window.CM == null){ window.CM = {}; } window.CM.Loader = this; let scope = this; head.ready(document, function() { head.load([ "/assets/css/app.css", "/assets/js/app.js", "/assets/js/shim.js", "//fast.fonts.com/cssapi/6536d2ad-a624-4b33-9405-4c303cfb6253.css" ], CM.Loader.startApplication); }); } removeGFX (){ document.body.setAttribute("class", document.body.getAttribute("class").split("hideloader").join("run")); CM.App.showPage(); let preloader = document.getElementsByClassName("preloader")[0]; if(preloader && preloader.parentNode){ preloader.parentNode.removeChild(preloader); } } startApplication (){ if(window.CM.App == undefined){ setTimeout(CM.Loader.startApplication, 500); } else { CM.App.blastoff(); document.body.setAttribute("class", document.body.getAttribute("class").split("loading").join("loaded") ); setTimeout(function(){ document.body.setAttribute("class", document.body.getAttribute("class").split("loaded").join("hideloader") ); }, 500); setTimeout(function(){ CM.Loader.removeGFX(); }, 1750); } } }; export default new Loader();
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */ jQuery(document).ready(function($) { var populate_modal = function(data, textStatus, jqXHR) { // Wrap the data object in jquery object var body = $("<div/>").html(data); // Remove the first heading from the returned data var header = body.find("h1, h2, h3, h4, h5, h6").eq(0).remove(); // Remove the first submit button from the returned data var footer = body.find("form").find("input[type=submit]").eq(0).remove(); // Add in content if (header) $("#modal").find("[data-role=modal-title-content]").text(header.text()); if (body) $("#modal").find("[data-role=modal-body-content]").html(body.html()); if (footer) $("#modal").find("[data-role=modal-footer-content]").html(footer); // Toggle the ajax-loader $("#modal").find(".ajax-loader").hide(); } var cleanup_modal = function() { $("#modal").find("[data-role=modal-title-content]").text(''); $("#modal").find("[data-role=modal-body-content]").text(''); $("#modal").find("[data-role=modal-footer-content]").text(''); $("#modal").find(".ajax-loader").hide(); } var display_modal = function(event) { event.preventDefault(); cleanup_modal(); $("#modal").find(".ajax-loader").show(); $("#modal").modal("show"); $.get(this.href, "", populate_modal, "html"); } var ajax_form_catch = function(event) { event.preventDefault(); $("#modal").find(".ajax-loader").show(); var form = $("#modal").find("form"); $.post(form.attr("action"), form.serialize(), populate_modal, "html"); cleanup_modal(); }; $(document).on("click", "a.ajax_window", display_modal); $(document).on("click", "#modal .modal-footer input[type=submit]", ajax_form_catch); $(document).on("submit", "#modal form", ajax_form_catch); });
'use strict'; moduloCategoria.factory('categoriaService', ['serverService', function (serverService) { return { getFields: function () { return [ {name: "id", shortname: "ID", longname: "Identificador", visible: true, type: "id"}, {name: "nombre", shortname: "Nombre", longname: "Nombre", visible: true, type: "text", required: true,pattern: serverService.getRegExpr("alpha-numeric"), help: serverService.getRegExpl("alpha-numeric")}, ]; }, getIcon: function () { return "fa-tags"; }, getObTitle: function () { return "categoria"; }, getTitle: function () { return "categoria"; } }; }]);
var ConfigInitializer = { name: 'config', initialize: function (container, application) { var apps = $('body').data('apps'), tagsUI = $('body').data('tagsui'), fileStorage = $('body').data('filestorage'), blogUrl = $('body').data('blogurl'), blogTitle = $('body').data('blogtitle'); application.register( 'ghost:config', {apps: apps, fileStorage: fileStorage, blogUrl: blogUrl, tagsUI: tagsUI, blogTitle: blogTitle}, {instantiate: false} ); application.inject('route', 'config', 'ghost:config'); application.inject('controller', 'config', 'ghost:config'); application.inject('component', 'config', 'ghost:config'); } }; export default ConfigInitializer;
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; var u = undefined; function plural(n) { var i = Math.floor(Math.abs(n)); if (i === 0 || i === 1) return 1; return 5; } global.ng.common.locales['fr-vu'] = [ 'fr-VU', [['AM', 'PM'], u, u], u, [ ['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'], ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'], ['di', 'lu', 'ma', 'me', 'je', 've', 'sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.' ], [ 'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre' ] ], u, [['av. J.-C.', 'ap. J.-C.'], u, ['avant Jésus-Christ', 'après Jésus-Christ']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1} {0}', '{1} \'à\' {0}', u, u], [',', '\u202f', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], 'VUV', 'VT', 'vatu vanuatuan', { 'ARS': ['$AR', '$'], 'AUD': ['$AU', '$'], 'BEF': ['FB'], 'BMD': ['$BM', '$'], 'BND': ['$BN', '$'], 'BZD': ['$BZ', '$'], 'CAD': ['$CA', '$'], 'CLP': ['$CL', '$'], 'CNY': [u, '¥'], 'COP': ['$CO', '$'], 'CYP': ['£CY'], 'EGP': [u, '£E'], 'FJD': ['$FJ', '$'], 'FKP': ['£FK', '£'], 'FRF': ['F'], 'GBP': ['£GB', '£'], 'GIP': ['£GI', '£'], 'HKD': [u, '$'], 'IEP': ['£IE'], 'ILP': ['£IL'], 'ITL': ['₤IT'], 'JPY': [u, '¥'], 'KMF': [u, 'FC'], 'LBP': ['£LB', '£L'], 'MTP': ['£MT'], 'MXN': ['$MX', '$'], 'NAD': ['$NA', '$'], 'NIO': [u, '$C'], 'NZD': ['$NZ', '$'], 'RHD': ['$RH'], 'RON': [u, 'L'], 'RWF': [u, 'FR'], 'SBD': ['$SB', '$'], 'SGD': ['$SG', '$'], 'SRD': ['$SR', '$'], 'TOP': [u, '$T'], 'TTD': ['$TT', '$'], 'TWD': [u, 'NT$'], 'USD': ['$US', '$'], 'UYU': ['$UY', '$'], 'VUV': ['VT'], 'WST': ['$WS'], 'XCD': [u, '$'], 'XPF': ['FCFP'], 'ZMW': [u, 'Kw'] }, 'ltr', plural, [ [ ['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u, ['minuit', 'midi', 'du matin', 'de l’après-midi', 'du soir', 'du matin'] ], [ ['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u, ['minuit', 'midi', 'matin', 'après-midi', 'soir', 'nuit'] ], [ '00:00', '12:00', ['04:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'], ['00:00', '04:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
/** * @param {string} s * @return {boolean} */ const checkValidString = function (s) { let leftCount = 0, rightCount = 0, starCount = 0; let idx = 0; while (idx < s.length) { let ch = s[idx++]; if (ch === '(') { ++leftCount; } else if (ch === '*') { ++starCount; } else { // ch === ')' ++rightCount; if (rightCount > leftCount + starCount) { return false; } } } idx = s.length - 1; leftCount = rightCount = starCount = 0; while (idx >= 0) { let ch = s[idx--]; if (ch === ')') { ++rightCount; } else if (ch === '*') { ++starCount; } else { // ch === '(' ++leftCount; if (leftCount > rightCount + starCount) { return false; } } } return true; }; module.exports = checkValidString;
// noinspection JSUnusedLocalSymbols const React = require('react') const moment = require('moment') const agent = require('../agent') import {Link} from 'react-router' import {Row, Col} from 'react-bootstrap' import ClientForm from './ClientForm' import _ from 'underscore' class RegisterClient extends React.Component { constructor (props, context) { super(props) this.state = {} } save () { let client = JSON.parse(JSON.stringify(_(this.state).omit(['loading']))) client.dob = moment(client.dob).valueOf() this.setState({loading: true}) agent.post('/services/clients') .send(client) .then(({body}) => { body.saved = true this.setState(body) if (this.props.location.query.returnTo) { this.props.router.push({ pathname: `${this.props.location.query.returnTo}/${body.id}` }) } }) .catch((error) => { console.error(error) this.setState(client) }) } render () { const {query} = this.props.location const state = this.state return ( <div className='container'> <Row> <Col> <h1> <span>Register a New Client </span> <small> <span>or </span> <Link to={{pathname: `/clients/locate`, query: query}}>find an existing client</Link> </small> </h1> </Col> </Row> <ClientForm {...state} setState={(x) => this.setState(x)} save={() => this.save()} location={this.props.location} history={this.props.history} /> </div> ) } } RegisterClient.propTypes = { location: React.PropTypes.object, history: React.PropTypes.object, router: React.PropTypes.object } export default RegisterClient
/** * Created by liushuo on 17/2/20. */ import React , {Component} from 'react'; import {AppRegistry , ListView , Text , View, StyleSheet,TouchableOpacity, Image, Dimensions} from 'react-native'; let badgeDatas = require('../Json/BadgeData.json') let {width,height,scale} = Dimensions.get("window"); let cols = 3; let bWidth = 100; let hM = (width - 3 * bWidth) / (cols + 1) let vM = 25; export default class BagImageDemo extends Component { renderAllBadge(){ let allBadgeDatas = []; for (let i = 0; i<badgeDatas.data.length;i++){ let data = badgeDatas.data[i]; allBadgeDatas.push( <View key={i} style={styles.outViewStyle}> <Image style={styles.imageStyle} source={{uri:data.icon}}></Image> <Text style={styles.bottomTextsStyle}>{data.title}</Text> </View> ); } return allBadgeDatas; } render() { return ( <View style={styles.contain}> {/*返回所有数据包*/} {this.renderAllBadge()} </View> ) } } const styles = StyleSheet.create({ contain:{ backgroundColor:'#F5FCFF', flexDirection:"row", flexWrap:'wrap', }, outViewStyle:{ width:bWidth, height: bWidth, marginLeft:hM, marginTop:vM, backgroundColor:'red', alignItems:"center" }, imageStyle:{ width:80, height:80 }, bottomTextsStyle:{ fontSize:12 } });
$ = require("jquery"); jQuery = require("jquery"); var StatusTable = require("./content/status-table"); var ArchiveTable = require("./content/archive-table"); var FailuresTable = require("./content/failures-table"); var UploadTestFile = require("./content/upload-test-file"); var UploadCredentials = require("./content/upload-credentials"); var UploadServerInfo = require("./content/upload-server-info"); var UploadBatch = require("./content/upload-batch"); var Bluebird = require("bluebird"); var StandardReport = require("./content/standard-report"); var JmeterReportTable = require("./content/jmeter-report-table"); require('expose?$!expose?jQuery!jquery'); require("bootstrap-webpack"); require('./vendor/startbootstrap-sb-admin-2-1.0.8/deps'); require("./vendor/startbootstrap-sb-admin-2-1.0.8/dist/js/sb-admin-2"); var ss = require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/bootstrap/dist/css/bootstrap.min.css").toString(); ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/metisMenu/dist/metisMenu.min.css").toString(); ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/dist/css/sb-admin-2.css").toString(); ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/font-awesome/css/font-awesome.min.css").toString(); ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/datatables/media/css/dataTables.jqueryui.min.css").toString(); function GetQueryStringParams(sParam){ var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++){ var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam){ return sParameterName[1]; } } } //module.exports = function(){ $(document).ready(function(){ $("<style></style>").text(ss).appendTo($("head")); new UploadTestFile($("form")); //new SwimLanes($("#swimlanes")); new UploadCredentials($("#credentials")); new UploadServerInfo($("#server-info")); new UploadBatch($("#batch")); if($("#batches-status")){ new StatusTable($("#batches-status"), "batches"); } if($("#runs-status")){ new StatusTable($("#runs-status"), "runs"); } if($("#standard-report")){ if(GetQueryStringParams("batchId")){ var batchId = GetQueryStringParams("batchId"); new StandardReport($("#standard-report"), batchId); new JmeterReportTable($("#jmeter-report-table"), batchId); } else { new FailuresTable($("#failures-table")); new ArchiveTable($("#archive-table")); } } }); //}
Meteor.publish('movieDetails.user', publishUserMovieDetails); function publishUserMovieDetails({ movieId }) { validate(); this.autorun(autorun); return; function validate() { new SimpleSchema({ movieId: ML.fields.id }).validate({ movieId }); } function autorun(computation) { if (!this.userId) { return this.ready(); } else { return Movies.find({ _id: movieId }, { fields: Movies.publicFields }); } } }
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'ul', classNames: 'ember-autocomplete-list', });
/** * Widget Footer Directive */ angular .module('Home') .directive('rdWidgetFooter', rdWidgetFooter); function rdWidgetFooter() { var directive = { requires: '^rdWidget', transclude: true, template: '<div class="widget-footer" ng-transclude></div>', restrict: 'E' }; return directive; };
game.PlayScreen = me.ScreenObject.extend({ /** * action to perform on state change */ onResetEvent: function() { // reset the score game.data.score = 0; me.levelDirector.loadLevel("level01"); this.resetPlayer(0, 420); // the level i'm going to load // levelDirector is telling it what to look at var gameTimerManager = me.pool.pull("GameTimerManager", 0, 0, {}); me.game.world.addChild(gameTimerManager, 0); // this adds the player to the screen var heroDeathManager = me.pool.pull("HeroDeathManager", 0, 0, {}); me.game.world.addChild(heroDeathManager, 0); var experienceManager = me.pool.pull("ExperienceManager", 0, 0, {}); me.game.world.addChild(experienceManager, 0); me.input.bindKey(me.input.KEY.RIGHT, "right"); me.input.bindKey(me.input.KEY.LEFT, "left"); me.input.bindKey(me.input.KEY.SPACE, "jump"); me.input.bindKey(me.input.KEY.A, "attack"); // add our HUD to the game world this.HUD = new game.HUD.Container(); me.game.world.addChild(this.HUD); }, /** * action to perform when leaving this screen (state change) */ onDestroyEvent: function() { // remove the HUD from the game world me.game.world.removeChild(this.HUD); }, resetPlayer: function(x, y){ game.data.player = me.pool.pull("player", x, y, {}); me.game.world.addChild(game.data.player, 5); } }); // where the game starts
Palette = function(name,colors){ this.name = name; this.colors = colors; }; Palette.prototype.hasName = function(name){ return this.name.toLowerCase() == name.toLowerCase()?true:false; }; Palette.prototype.getRandomColor = function(){ return this.colors[(Math.floor(Math.random() * this.colors.length))]; }; Palette.prototype.getName = function(){ return this.name; }; Palette.prototype.setName = function(name){ this.name = name; }; Palette.prototype.getColors = function(){ return this.colors; }; Palette.prototype.setColors = function(colors){ this.colors = colors; }; Palette.generateRandomPalette = function(){ var colors = []; for(var i = 0; i< 5; i++){ colors.push(('#'+Math.floor(Math.random()*16777215).toString(16)).toUpperCase()); } return new Palette("RandomizePalette",colors); };
'use strict'; const inflect = require('i')(); const _ = require('lodash'); const Promise = require('bluebird'); const fs = Promise.promisifyAll(require('fs')); const options = { adapter: 'mongodb', connectionString: 'mongodb://127.0.0.1:27017/testDB', db: 'testDB', inflect: true }; console.log(JSON.stringify(options)); const runningAsScript = !module.parent; /* *** Elastic-Search mapping maker. *** * -------------------------------- * Generate scaffolded elastic-search mapping from a harvester app. Meant to be run @cmd line, but can also be required and used in code. #Usage: node mappingMaker.js path-to-harvester-app primary-es-graph-resource(e.g. people) file-to-create.json NB: argv[3] (in this case, "file-to-create.json") is optional. If not specified, no file will be written to disk; instead the mapping will be console.logged. */ const functionTypeLookup = { 'function Stri': 'string', 'function Numb': 'number', 'function Bool': 'boolean', 'function Date': 'date', 'function Buff': 'buffer', 'function Arra': 'array' }; function getFunctionType(fn) { return functionTypeLookup[fn.toString().substr(0, 13)]; } function MappingMaker() { } MappingMaker.prototype.generateMapping = function generateMapping(harvestApp, pov, outputFile) { let harvesterApp; if (_.isString(harvestApp)) { harvesterApp = require(harvestApp)(options); } else { harvesterApp = Promise.resolve(harvestApp); } return harvesterApp .catch() // harvestApp doesn't have to work perfectly; we just need its schemas. .then((_harvesterApp) => { return make(_harvesterApp, pov); }) .then((mappingData) => { if (outputFile) { console.log(`Saving mapping to ${outputFile}`); return fs.writeFileAsync(outputFile, JSON.stringify(mappingData, null, 4)).then(() => { console.log('Saved.'); return mappingData; }).error((e) => { console.error('Unable to save file, because: ', e.message); }); } console.log('Generated Mapping: '); console.log(JSON.stringify(mappingData, null, 4)); return mappingData; }); }; function make(harvestApp, pov) { const schemaName = inflect.singularize(pov); const startingSchema = harvestApp._schema[schemaName]; const maxDepth = 4; const _depth = 0; const retVal = {}; retVal[pov] = { properties: {} }; const _cursor = retVal[pov].properties; function getNextLevelSchema(propertyName, propertyValue, cursor, depth) { let nextCursor; if (depth === 1) { cursor.links = cursor.links || { type: 'nested' }; cursor.links.properties = cursor.links.properties || {}; cursor.links.properties[propertyName] = { type: 'nested', properties: {} }; nextCursor = cursor.links.properties[propertyName].properties; } else { if (depth === maxDepth) { return; } cursor[propertyName] = { type: 'nested', properties: {} }; nextCursor = cursor[propertyName].properties; } harvestApp._schema[propertyValue] && getLinkedSchemas(harvestApp._schema[propertyValue], nextCursor, depth); } function getLinkedSchemas(_startingSchema, cursor, depth) { if (depth >= maxDepth) { console.warn(`[Elastic-harvest] Graph depth of ${depth} exceeds ${maxDepth}. Graph dive halted prematurely` + ' - please investigate.'); // harvest schema may have circular references. return null; } const __depth = depth + 1; _.each(_startingSchema, (propertyValue, propertyName) => { if (typeof propertyValue !== 'function') { if (_.isString(propertyValue)) { getNextLevelSchema(propertyName, propertyValue, cursor, __depth); } else if (_.isArray(propertyValue)) { if (_.isString(propertyValue[0])) { getNextLevelSchema(propertyName, propertyValue[0], cursor, __depth); } else { getNextLevelSchema(propertyName, propertyValue[0].ref, cursor, __depth); } } else if (_.isObject(propertyValue)) { getNextLevelSchema(propertyName, propertyValue.ref, cursor, __depth); } } else { const fnType = getFunctionType(propertyValue); if (fnType === 'string') { cursor.id = { type: 'string', index: 'not_analyzed' }; cursor[propertyName] = { type: 'string', index: 'not_analyzed' }; } else if (fnType === 'number') { cursor[propertyName] = { type: 'long' }; } else if (fnType === 'date') { cursor[propertyName] = { type: 'date' }; } else if (fnType === 'boolean') { cursor[propertyName] = { type: 'boolean' }; } else if (fnType === 'array') { console.warn('[mapping-maker] Array-type scaffolding not yet implemented; ' + `The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`); } else if (fnType === 'buffer') { console.warn('[mapping-maker] Buffer-type scaffolding not yet implemented; ' + `The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`); } else { console.warn('[mapping-maker] unsupported type; ' + `The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`); } } }); return cursor; } getLinkedSchemas(startingSchema, _cursor, _depth); return retVal; } if (runningAsScript) { const mappingMaker = new MappingMaker(); mappingMaker.generateMapping(process.argv[2], process.argv[3], process.argv[4]); } else { module.exports = MappingMaker; }
function noReservedDays(date) { var m = date.getMonth(), d = date.getDate(), y = date.getFullYear(); for (i = 0; i < reservedDays.length; i++) { if ($.inArray((m + 1) + '-' + d + '-' + y, reservedDays) !== -1) { return [false]; } } return [true]; } $("#input_from").datepicker({ dayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], dayNamesShort: ["Son", "Mon", "Din", "Mit", "Don", "Fra", "Sam"], dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], monthNames: ["Januar", "Februar", ";ärz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], monthNamesShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sept", "Okt", "Nov", "Dez"], firstDay: 1, dateFormat: "dd.mm.yy", constrainInput: true, beforeShowDay: noReservedDays, minDate: 0, onSelect: function(selected) { $("#input_until").datepicker("option", "minDate", selected); } }); $("#input_until").datepicker({ dayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], dayNamesShort: ["Son", "Mon", "Din", "Mit", "Don", "Fra", "Sam"], dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], monthNames: ["Januar", "Februar", ";ärz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], monthNamesShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sept", "Okt", "Nov", "Dez"], firstDay: 1, dateFormat: "dd.mm.yy", constrainInput: true, beforeShowDay: noReservedDays, minDate: 1, onSelect: function(selected) { $("#input_from").datepicker("option", "maxDate", selected); } });
define([], function() { function System(options) { var options = options || {}, requirements = options.requires ? options.requires.slice(0).sort() : []; return { getRequirements: function() { return requirements; }, init: options.init || function() {}, shutdown: options.shutdown || function() {}, update: options.update || function(game, entities) { for (var i = 0, len = entities.length; i < len; ++i) { this.updateEach(game, entities[i]); } }, updateEach: options.updateEach }; } return System; });
module.exports = ({ config }, options = {}) => config.module .rule('style') .test(/\.css$/) .use('style') .loader(require.resolve('style-loader')) .when(options.style, use => use.options(options.style)) .end() .use('css') .loader(require.resolve('css-loader')) .when(options.css, use => use.options(options.css));
/** * Created by Kaloyan on 24.5.2015 ã.. */ console.log('============'); console.log('Exercise 1: Exchange if first is greater'); var a = 5; var b = 2; if (a > b) { var temp = a; a = b; b = temp; } console.log(a + ' ' + b);
'use strict'; var express = require('express'), logger = require('morgan'), bodyParser = require('body-parser'), stylus = require('stylus'), cookieParser = require('cookie-parser'), session = require('express-session'), passport = require('passport'); module.exports = function(app, config) { function compile(str, path) { // compile function for stylus return stylus(str).set('filename', path); } app.set('views', config.rootPath + '/server/views'); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(cookieParser()); app.use(bodyParser()); app.use(session({secret: 'multi vision unicorns'})); app.use(passport.initialize()); app.use(passport.session()); app.use(stylus.middleware( { src: config.rootPath + '/public', compile: compile } )); app.use(express.static(config.rootPath + '/public')); }
/** * Created by cin on 1/18/14. */ /** * Created by cin on 1/18/14. */ var _ = require('underscore'), chance = new (require('chance'))(), syBookshelf = require('./base'), User = require('./user'), CoStatus = require('./co-status'), UserCooperation = require('./user-cooperation'), UserCooperations = UserCooperation.Set, Picture = require('./picture'), Pictures = Picture.Set, CoComment = require('./co-comment'), Cooperation, Cooperations, config = require('../config'), tbCooperation = 'cooperations', fkStatus = 'statusid', fkCooperation = 'cooperationid', fkOwner = 'ownerid'; Cooperation = module.exports = syBookshelf.Model.extend({ tableName: tbCooperation, fields: [ 'id', 'name', 'description', 'company', 'avatar', 'statusid', 'ownerid', 'isprivate', 'regdeadline', 'createtime' ], appended: ['user', 'status'], fieldToAssets: { avatar: 'cooperations' }, defaults: function () { return { createtime: new Date() } }, toJSON: function () { var self = this, Model = this.constructor, ret = Model.__super__.toJSON.apply(this, arguments); _.each(this.fieldToAssets, function (type, field) { if (self.get(field) != null) { var file = self.getAssetPath(type); ret[field] = config.toStaticURI(file) + '?t=' + ret[field]; } }); return ret; }, saving: function () { return Cooperation.__super__ .saving.apply(this, arguments); }, usership: function () { return this.hasMany(UserCooperations, fkCooperation); }, fetched: function (model, attrs, options) { return Cooperation.__super__.fetched.apply(this, arguments) .return(model) .call('countComments') .call('countUsership') .call('countPictures') .then(function (cooperation) { return model.related('pictures').fetch(); }) .then(function () { if (!options['detailed']) return; return model.related('cocomments') .query(function (qb) { qb.orderBy('id', 'desc'); }).fetch(); }) }, countUsership: function () { var self = this; return this.usership().fetch() .then(function (userships) { var numUserships = userships.length; return self.data('numUserships', numUserships); }) }, status: function () { return this.belongsTo(CoStatus, fkStatus); }, user: function () { return this.belongsTo(require('./user'), fkOwner); }, cocomments: function () { return this.hasMany(CoComment, 'cooperationid'); }, pictures: function () { return this.hasMany(Picture, 'cooperationid'); }, countComments: function () { var self = this; return this.cocomments().fetch() .then(function (cocomments) { var numComments = cocomments.length; return self.data('numComments', numComments); }); }, countPictures: function () { var self = this; return Pictures.forge().query() .where(fkCooperation, '=', self.id) .count('id') .then(function (d) { return self.data('numPictures', d[0]["count(`id`)"]); }); } }, { randomForge: function () { var status = _.random(1, 2); return Cooperation.forge({ 'name': chance.word(), 'description': chance.paragraph(), 'ownerid': chance.integer({ min: 1, max: 20 }), 'company': chance.word(), 'avatar': chance.word(), 'statusid': status, 'isprivate': chance.bool(), 'regdeadline': chance.date({ year: 2013 }) }); } }); Cooperations = Cooperation.Set = syBookshelf.Collection.extend({ model: Cooperation, lister: function (req, qb) { var query = req.query; this.qbWhere(qb, req, query, ['id', 'statusid', 'ownerid', 'isprivate'], tbCooperation); if (!req.query['fuzzy']) { this.qbWhere(qb, req, query, ['name', 'company'], tbCooperation); } else { this.qbWhereLike(qb, req, query, ['name', 'description', 'company'], tbCooperation); } } });
'use strict'; var mongoose = require('mongoose'); require('./models/StockPoint'); require('./models/Pattern'); var mongoDbURL = 'mongodb://localhost/pttnrs'; if (process.env.MONGOHQ_URL) { mongoDbURL = process.env.MONGOHQ_URL; } mongoose.connect(mongoDbURL);
// Copyright IBM Corp. 2014. All Rights Reserved. // Node module: async-tracker // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT var assert = require('assert'); require('../index.js'); var fs = require('fs'); var util = require('util'); var cnt = 0; var Listener = function() { var evtName = asyncTracker.events.fs.open; this.deferredCreated = {}; this.invokeDeferred = {}; this.deferredReleased = {}; this.deferredCreated[evtName] = function(fName, fId, args) { assert.equal(cnt, 0); cnt += 1; }; this.deferredCreated['default'] = function(fName, fId, args) { assert.equal(cnt, 4); cnt += 1; }; this.invokeDeferred[evtName] = function(fName, fId, next) { assert.equal(cnt, 2); cnt += 1; next(); }; this.invokeDeferred['default'] = function(fName, fId, next) { assert.equal(cnt, 6); cnt += 1; next(); }; this.deferredReleased[evtName] = function(fName, fId) { assert.equal(cnt, 5); cnt += 1; }; this.deferredReleased['default'] = function(fName, fId) { assert.equal(cnt, 7); cnt += 1; }; this.objectCreated = function(obj) { assert.equal(cnt, 1); cnt += 1; }; this.objectReleased = function(obj) { assert.equal(cnt, 3); cnt += 1; }; }; var listener = new Listener(); asyncTracker.addListener(listener, 'listener'); function closeCallback() { } function openCallback(err, fd) { fs.close(fd, closeCallback); } fs.open(__filename, 'r', openCallback); asyncTracker.removeListener('listener');
var prettyURLs = require('../middleware/pretty-urls'), cors = require('../middleware/api/cors'), urlRedirects = require('../middleware/url-redirects'), auth = require('../../auth'); /** * Auth Middleware Packages * * IMPORTANT * - cors middleware MUST happen before pretty urls, because otherwise cors header can get lost on redirect * - cors middleware MUST happen after authenticateClient, because authenticateClient reads the trusted domains * - url redirects MUST happen after cors, otherwise cors header can get lost on redirect */ /** * Authentication for public endpoints */ module.exports.authenticatePublic = [ auth.authenticate.authenticateClient, auth.authenticate.authenticateUser, // This is a labs-enabled middleware auth.authorize.requiresAuthorizedUserPublicAPI, cors, urlRedirects, prettyURLs ]; /** * Authentication for private endpoints */ module.exports.authenticatePrivate = [ auth.authenticate.authenticateClient, auth.authenticate.authenticateUser, auth.authorize.requiresAuthorizedUser, cors, urlRedirects, prettyURLs ]; /** * Authentication for client endpoints */ module.exports.authenticateClient = function authenticateClient(client) { return [ auth.authenticate.authenticateClient, auth.authenticate.authenticateUser, auth.authorize.requiresAuthorizedClient(client), cors, urlRedirects, prettyURLs ]; };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var SearchBar = function (_Component) { _inherits(SearchBar, _Component); function SearchBar(props) { _classCallCheck(this, SearchBar); var _this = _possibleConstructorReturn(this, (SearchBar.__proto__ || Object.getPrototypeOf(SearchBar)).call(this, props)); _this.state = { term: '' }; _this.onInputChange = _this.onInputChange.bind(_this); return _this; } _createClass(SearchBar, [{ key: 'onInputChange', value: function onInputChange(term) { this.setState({ term: term }); this.props.getResults(term); } }, { key: 'render', value: function render() { var _this2 = this; return _react2.default.createElement( 'div', { className: 'searchBarContainer' }, _react2.default.createElement('input', { type: 'text', value: this.state.term, onChange: function onChange(event) { return _this2.onInputChange(event.target.value); } }) ); } }]); return SearchBar; }(_react.Component); exports.default = SearchBar; {/*<button><i id="searchIcon" className="fa fa-search" /></button>*/} //# sourceMappingURL=searchbar-compiled.js.map
var SuperheroesShowRoute = Ember.Route.extend({ model: function(params) { return(this.store.find('superhero', params.id)); } }); export default SuperheroesShowRoute;
{ if (this.props.x === 227) { return React.createElement( "span", { className: "_38my" }, "Campaign Details", null, React.createElement("span", { className: "_c1c" }) ); } if (this.props.x === 265) { return React.createElement( "span", { className: "_38my" }, [ React.createElement( "span", { key: 1 }, "Campaign ID", ": ", "98010048849317" ), React.createElement( "div", { className: "_5lh9", key: 2 }, React.createElement( FluxContainer_AdsCampaignGroupStatusSwitchContainer_119, { x: 264 } ) ) ], null, React.createElement("span", { className: "_c1c" }) ); } }
const Discord = require("discord.js"); const client = new Discord.Client(); const settings = require("./settings.json"); const chalk = require("chalk"); const fs = require("fs"); const moment = require("moment"); require("./util/eventLoader")(client); const log = message => { console.log(`[${moment().format("YYYY-MM-DD HH:mm:ss")}] ${message}`); }; client.commands = new Discord.Collection(); client.aliases = new Discord.Collection(); fs.readdir('./commands/', (err, files) => { if (err) console.error(err); log(`Loading a total of ${files.length} commands.`); files.forEach(f => { let props = require(`./commands/${f}`); log(`Loading Command: ${props.help.name}. 👌`); client.commands.set(props.help.name, props); props.conf.aliases.forEach(alias => { client.aliases.set(alias, props.help.name); }); }); }); client.reload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./commands/${command}`)]; let cmd = require(`./commands/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.on("ready", () => { const games = ["Not a Game", "The Joker Game Returns", "The Coven", "Nintendo: Choose Your Own Character 2!", "PokéDonalds"]; setInterval(() => { const playingGame = games[~~(Math.random() * games.length)]; console.log(`Changing playing game to ${playingGame} now`); client.user.setGame(playingGame); }, 1800000); client.channels.get("339257481740156928").fetchMessages({ limit: 30 }) .then(messages => console.log(`Received ${messages.size} messages`)) .catch(console.error); }); client.elevation = message => { /* This function should resolve to an ELEVATION level which is then sent to the command handler for verification*/ let permlvl = 0; let mod_role = message.guild.roles.find("name", settings.modrolename); if (mod_role && message.member.roles.has(mod_role.id)) permlvl = 2; let admin_role = message.guild.roles.find("name", settings.adminrolename); if (admin_role && message.member.roles.has(admin_role.id)) permlvl = 3; if (message.author.id === settings.ownerid) permlvl = 4; return permlvl; }; let autoResponse = { "ayy": "lmao", "ayyy": "lmao", "ayyyy": "lmao", "that's hot": "eso es caliente", "lenny": "( ͡° ͜ʖ ͡°)", "eso es caliente": "that's hot", "drewbie": "!kick drewbie" }; client.on("message", message => { if (message.content === "lala") { console.log(guild.members.find(nickname, 'asd')); } if (message.author.bot) return; let msg = message.content.toLowerCase(); if (autoResponse[msg]) { message.channel.send(autoResponse[msg]); } }); var regToken = /[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g; // client.on('debug', e => { // console.log(chalk.bgBlue.green(e.replace(regToken, 'that was redacted'))); // }); client.on("warn", e => { console.log(chalk.bgYellow(e.replace(regToken, "that was redacted"))); }); client.on("error", e => { console.log(chalk.bgRed(e.replace(regToken, "that was redacted"))); }); client.login(process.env.TOKEN);
import React from 'react'; import { storiesOf } from '@storybook/react'; import moment from 'moment'; import { withKnobs, number, object, boolean, text, select, date, array, color, files, } from '../../src'; const stories = storiesOf('Example of Knobs', module); stories.addDecorator(withKnobs); stories.add('simple example', () => <button>{text('Label', 'Hello Button')}</button>); stories.add('with all knobs', () => { const name = text('Name', 'Tom Cary'); const dob = date('DOB', new Date('January 20 1887')); const bold = boolean('Bold', false); const selectedColor = color('Color', 'black'); const favoriteNumber = number('Favorite Number', 42); const comfortTemp = number('Comfort Temp', 72, { range: true, min: 60, max: 90, step: 1 }); const passions = array('Passions', ['Fishing', 'Skiing']); const images = files('Happy Picture', 'image/*', [ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQfiARwMCyEWcOFPAAAAP0lEQVQoz8WQMQoAIAwDL/7/z3GwghSp4KDZyiUpBMCYUgd8rehtH16/l3XewgU2KAzapjXBbNFaPS6lDMlKB6OiDv3iAH1OAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE4LTAxLTI4VDEyOjExOjMzLTA3OjAwlAHQBgAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxOC0wMS0yOFQxMjoxMTozMy0wNzowMOVcaLoAAAAASUVORK5CYII=', ]); const customStyle = object('Style', { fontFamily: 'Arial', padding: 20, }); const style = { ...customStyle, fontWeight: bold ? 800 : 400, favoriteNumber, color: selectedColor, }; return ( <div style={style}> I'm {name} and I was born on "{moment(dob).format('DD MMM YYYY')}" I like:{' '} <ul>{passions.map(p => <li key={p}>{p}</li>)}</ul> <p>My favorite number is {favoriteNumber}.</p> <p>My most comfortable room temperature is {comfortTemp} degrees Fahrenheit.</p> <p> When I am happy I look like this: <img src={images[0]} alt="happy" /> </p> </div> ); }); stories.add('dates Knob', () => { const today = date('today'); const dob = date('DOB', null); const myDob = date('My DOB', new Date('July 07 1993')); return ( <ul style={{ listStyleType: 'none', listStyle: 'none', paddingLeft: '15px' }}> <li> <p> <b>Javascript Date</b> default value, passes date value </p> <blockquote> <code>const myDob = date('My DOB', new Date('July 07 1993'));</code> <pre>{`// I was born in: "${moment(myDob).format('DD MMM YYYY')}"`}</pre> </blockquote> </li> <li> <p> <b>undefined</b> default value passes today's date </p> <blockquote> <code>const today = date('today');</code> <pre>{`// Today's date is: "${moment(today).format('DD MMM YYYY')}"`}</pre> </blockquote> </li> <li> <p> <b>null</b> default value passes null value </p> <blockquote> <code>const dob = date('DOB', null);</code> <pre> {`// You were born in: "${ dob ? moment(dob).format('DD MMM YYYY') : 'Please select date.' }"`} </pre> </blockquote> </li> </ul> ); }); stories.add('dynamic knobs', () => { const showOptional = select('Show optional', ['yes', 'no'], 'yes'); return ( <div> <div>{text('compulsary', 'I must be here')}</div> {showOptional === 'yes' ? <div>{text('optional', 'I can disapear')}</div> : null} </div> ); }); stories.add('without any knob', () => <button>This is a button</button>);
import { expect } from 'chai' import { describe, it } from 'mocha' import { or } from 'opensource-challenge-client/helpers/or' describe('Unit | Helper | or', function() { it('works', function() { expect(or([42, 42])).to.equal(true) expect(or([false, 42, false])).to.equal(true) expect(or([true, 42])).to.equal(true) expect(or([null, undefined, 1])).to.equal(true) }) })
/* */ define(['exports', './i18n', 'aurelia-event-aggregator', 'aurelia-templating', './utils'], function (exports, _i18n, _aureliaEventAggregator, _aureliaTemplating, _utils) { 'use strict'; exports.__esModule = true; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var TValueConverter = (function () { TValueConverter.inject = function inject() { return [_i18n.I18N]; }; function TValueConverter(i18n) { _classCallCheck(this, TValueConverter); this.service = i18n; } TValueConverter.prototype.toView = function toView(value, options) { return this.service.tr(value, options); }; return TValueConverter; })(); exports.TValueConverter = TValueConverter; var TParamsCustomAttribute = (function () { _createClass(TParamsCustomAttribute, null, [{ key: 'inject', value: [Element], enumerable: true }]); function TParamsCustomAttribute(element) { _classCallCheck(this, _TParamsCustomAttribute); this.element = element; } TParamsCustomAttribute.prototype.valueChanged = function valueChanged() {}; var _TParamsCustomAttribute = TParamsCustomAttribute; TParamsCustomAttribute = _aureliaTemplating.customAttribute('t-params')(TParamsCustomAttribute) || TParamsCustomAttribute; return TParamsCustomAttribute; })(); exports.TParamsCustomAttribute = TParamsCustomAttribute; var TCustomAttribute = (function () { _createClass(TCustomAttribute, null, [{ key: 'inject', value: [Element, _i18n.I18N, _aureliaEventAggregator.EventAggregator, _utils.LazyOptional.of(TParamsCustomAttribute)], enumerable: true }]); function TCustomAttribute(element, i18n, ea, tparams) { _classCallCheck(this, _TCustomAttribute); this.element = element; this.service = i18n; this.ea = ea; this.lazyParams = tparams; } TCustomAttribute.prototype.bind = function bind() { var _this = this; this.params = this.lazyParams(); setTimeout(function () { if (_this.params) { _this.params.valueChanged = function (newParams, oldParams) { _this.paramsChanged(_this.value, newParams, oldParams); }; } var p = _this.params !== null ? _this.params.value : undefined; _this.subscription = _this.ea.subscribe('i18n:locale:changed', function () { _this.service.updateValue(_this.element, _this.value, p); }); setTimeout(function () { _this.service.updateValue(_this.element, _this.value, p); }); }); }; TCustomAttribute.prototype.paramsChanged = function paramsChanged(newValue, newParams) { this.service.updateValue(this.element, newValue, newParams); }; TCustomAttribute.prototype.valueChanged = function valueChanged(newValue) { var p = this.params !== null ? this.params.value : undefined; this.service.updateValue(this.element, newValue, p); }; TCustomAttribute.prototype.unbind = function unbind() { this.subscription.dispose(); }; var _TCustomAttribute = TCustomAttribute; TCustomAttribute = _aureliaTemplating.customAttribute('t')(TCustomAttribute) || TCustomAttribute; return TCustomAttribute; })(); exports.TCustomAttribute = TCustomAttribute; });
class sppcomapi_elevationconfig_1 { constructor() { // ISPPLUA Elevated () {get} this.Elevated = undefined; // bool IsElevated () {get} this.IsElevated = undefined; // _ElevationConfigOptions Mode () {get} {set} this.Mode = undefined; // uint64 UIHandle () {set} this.UIHandle = undefined; } // void ConfigureObject (IUnknown) ConfigureObject(IUnknown) { } } module.exports = sppcomapi_elevationconfig_1;
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's // vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // // require rails-ujs //= require turbolinks //= require jquery //= require jquery_ujs //= require bootstrap-sprockets //= require bootstrap.file-input document.addEventListener("turbolinks:load", function() { if ($('.btn-file').length === 0) { $('input[type=file]').bootstrapFileInput(); $('.file-inputs').bootstrapFileInput(); } }); $(document).ready(function() { // Javascript for button validation $(document).on('click', 'input[type=radio]', function() { el = $(this); col = el.data("col"); el .parents(".table") .find("input[data-col=" + col + "]") .prop("checked", false); el.prop("checked", true); }) // Javascript for submit button validation $(document).on('click', '#quizSubmit', function() { var questions = validate_form(); if(questions.size == 0 ) { return; } else { questionString = ""; questions.forEach(function(value) { questionString = questionString + ", " + value; }); if (questions.size == 1) { alert("Please finish question" + questionString.substring(1) + " before submitting!"); } else { alert("Please finish questions" + questionString.substring(1) + " before submitting!"); } event.preventDefault(); } }) // Iterates through all answers and checks that they are ranked // Returns 0 if all are checked, otherwise returns first question that isn't finished function validate_form() { var numbers = new Set(); scroll = 0; for (i = 1; i < 19; i++) { $("#q" + i).css("border", "2px solid white"); for (j = 1; j < 5; j++) { name = "q" + i + "a" + j; if ($("input[name='" + name + "']:checked").length == 0) { numbers.add(i); $("#q" + i).css("border", "2px solid red"); if (scroll == 0) { var top = $('#q' + i).position().top; $(window).scrollTop( top - 75); //Offset because header blocks some of screen scroll = 1; } } } } return numbers; } // Prevents arrow keys from moving radio button $(document).on('click', 'input[type=radio]', function() { document.addEventListener("keydown", function (e) { if ([37].indexOf(e.keyCode) > -1) { // left e.preventDefault(); window.scrollBy(-50, -0); } if ([38].indexOf(e.keyCode) > -1) { //up e.preventDefault(); window.scrollBy(0, -50); } if ([39].indexOf(e.keyCode) > -1) { //right e.preventDefault(); window.scrollBy(50, 0); } if([40].indexOf(e.keyCode) > -1) { //down e.preventDefault(); window.scrollBy(0, 50); } }, false); }) });
version https://git-lfs.github.com/spec/v1 oid sha256:7678f6e4188a6066c45fd9a295882aea8e986bbc11eea3dbeabf24eca190b774 size 394
version https://git-lfs.github.com/spec/v1 oid sha256:d1ae7db9f7928706e5601ba8c7d71d4c9fbd1c4463c6b6465b502115eae45c07 size 77153
"use strict"; //////////////////////////////////////////////////////////////////////////////// // デスクトップ通知履歴 //////////////////////////////////////////////////////////////////////////////// Contents.notify_history = function( cp ) { var p = $( '#' + cp.id ); var cont = p.find( 'div.contents' ); var notify_history_list; var scrollPos = null; cp.SetIcon( 'icon-bubble' ); //////////////////////////////////////////////////////////// // リスト部作成 //////////////////////////////////////////////////////////// var ListMake = function( type ) { var s = ''; for ( var i = g_cmn.notsave.notify_history.length - 1 ; i >= 0 ; i-- ) { var assign = {}; for ( var arg in g_cmn.notsave.notify_history[i].data ) { try { assign[arg] = decodeURIComponent( g_cmn.notsave.notify_history[i].data[arg] ); } catch ( err ) { assign[arg] = g_cmn.notsave.notify_history[i].data[arg]; } } s += OutputTPL( 'notify_' + g_cmn.notsave.notify_history[i].type, assign ); } notify_history_list.html( s ) .scrollTop( 0 ); notify_history_list.find( '.notify' ).each( function() { var account_id = $( this ).attr( 'account_id' ); $( this ).find( '.notify_username' ).click( function( e ) { OpenUserTimeline( $( this ).attr( 'src' ), account_id ); e.stopPropagation(); } ); $( this ).find( '.notify_dmname' ).click( function( e ) { var _cp = new CPanel( null, null, 360, $( window ).height() * 0.75 ); _cp.SetType( 'timeline' ); _cp.SetParam( { account_id: account_id, timeline_type: 'dmrecv', reload_time: g_cmn.cmn_param['reload_time'], } ); _cp.Start(); e.stopPropagation(); } ); $( this ).find( '.notify_followname' ).click( function( e ) { var _cp = new CPanel( null, null, 320, 360 ); var num = $( this ).attr( 'num' ); _cp.SetType( 'follow' ); _cp.SetParam( { type: 'followers', account_id: account_id, screen_name: g_cmn.account[account_id].screen_name, number: num, } ); _cp.Start(); e.stopPropagation(); } ); $( this ).find( '.notify_listname' ).click( function( e ) { var _cp = new CPanel( null, null, 360, $( window ).height() * 0.75 ); _cp.SetType( 'timeline' ); _cp.SetParam( { account_id: account_id, timeline_type: 'list', list_id: $( this ).attr( 'list_id' ), screen_name: $( this ).attr( 'screen_name' ), slug: $( this ).attr( 'slug' ), reload_time: g_cmn.cmn_param['reload_time'], } ); _cp.Start(); e.stopPropagation(); } ); } ); cont.trigger( 'contents_resize' ); }; //////////////////////////////////////////////////////////// // 開始処理 //////////////////////////////////////////////////////////// this.start = function() { //////////////////////////////////////// // 最小化/設定切替時のスクロール位置 // 保存/復元 //////////////////////////////////////// cont.on( 'contents_scrollsave', function( e, type ) { // 保存 if ( type == 0 ) { if ( scrollPos == null ) { scrollPos = notify_history_list.scrollTop(); } } // 復元 else { if ( scrollPos != null ) { notify_history_list.scrollTop( scrollPos ); scrollPos = null; } } } ); //////////////////////////////////////// // リサイズ処理 //////////////////////////////////////// cont.on( 'contents_resize', function() { $( '#notify_history_list' ).height( cont.height() - cont.find( '.panel_btns' ).height() - 1 ); } ); // 全体を作成 cont.addClass( 'notify_history' ) .html( OutputTPL( 'notify_history', {} ) ); notify_history_list = $( '#notify_history_list' ); //////////////////////////////////////// // 更新ボタンクリック //////////////////////////////////////// $( '#notify_history_reload' ).click( function( e ) { // disabledなら処理しない if ( $( this ).hasClass( 'disabled' ) ) { return; } ListMake(); } ); // リスト部作成処理 ListMake(); }; //////////////////////////////////////////////////////////// // 終了処理 //////////////////////////////////////////////////////////// this.stop = function() { }; }
import net from 'net'; import log from './log.js'; export default function(options, onConnect) { // proxy server let proxy = net.createServer(function(client) { let server; // Create a new connection to the target server server = net.connect(options.port); // 2-way pipe between proxy and target server client.pipe(server).pipe(client); client.on('close', function() { server.end(); }); server.on('close', function() { client.end(); }); client.on('error', function(err) { log.error('Client: ' + err.toString()); client.end(); server.end(); }); server.on('error', function(err) { log.error('Server: ' + err.toString()); client.end(); server.end(); }); onConnect(client, server); }); proxy.listen(options.proxyPort); }
'use strict'; var util = require('util') , yeoman = require('yeoman-generator') , github = require('../lib/github') , path = require('path') , inflect = require('inflect'); var BBBGenerator = module.exports = function BBBGenerator(args, options, config) { // By calling `NamedBase` here, we get the argument to the subgenerator call // as `this.name`. yeoman.generators.NamedBase.apply(this, arguments); if (!this.name) { this.log.error('You have to provide a name for the subgenerator.'); process.exit(1); } this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); // Set destination root back to project root to help with testability this.destinationRoot('../../'); }); this.appName = this.name; this.destPath = util.format('client/%s', this.appName); }; util.inherits(BBBGenerator, yeoman.generators.NamedBase); BBBGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(this.yeoman); var prompts = [{ name: 'githubUser', message: 'Tell me again your username on Github?', default: 'someuser' },{ name: 'appDescription', message: 'Give this app a description', },{ name: 'version', message: 'What is the starting version number for this app you\'d like to use?', default: '0.1.0' }]; this.prompt(prompts, function (props) { this.githubUser = props.githubUser; this.appDescription = props.appDescription; this.version = props.version; cb(); }.bind(this)); }; BBBGenerator.prototype.userInfo = function userInfo() { var self = this , done = this.async(); github.githubUserInfo(this.githubUser, function (res) { /*jshint camelcase:false */ self.realname = res.name; self.email = res.email; self.githubUrl = res.html_url; done(); }); }; BBBGenerator.prototype.createDestFolder = function createDestFolder() { this.mkdir(this.destPath); this.destinationRoot(path.join(this.destinationRoot(), this.destPath)); }; BBBGenerator.prototype.fetchBoilerplate = function fetchBoilerplate() { var self = this , done = this.async(); this.remote('duro', 'clutch-backbone-boilerplate', function(err, remote) { self.sourceRoot(remote.cachePath); done(); }); }; BBBGenerator.prototype.buildApp = function buildSkeleton() { var self = this; this.directory('.','.'); };
import {mount, render, shallow} from 'enzyme'; global.mount = mount; global.render = render; global.shallow = shallow;
'use strict'; var _require = require('./parseProps'), parsePropTypes = _require.parsePropTypes, parseDefaultProps = _require.parseDefaultProps, resolveToValue = require('./util/resolveToValue'); module.exports = function (state) { var json = state.result, components = state.seen; var isAssigning = function isAssigning(node, name) { return node.operator === '=' && node.left.property && node.left.property.name === name; }; var seenClass = function seenClass(name, scope) { return components.indexOf(name) !== -1 && scope.hasBinding(name); }; return { enter: function enter(_ref) { var node = _ref.node, scope = _ref.scope; var component = node.left.object && node.left.object.name; if (isAssigning(node, 'propTypes') && seenClass(component, scope)) parsePropTypes(resolveToValue(node.right, scope), json[component], scope);else if (isAssigning(node, 'defaultProps') && seenClass(component, scope)) { parseDefaultProps(resolveToValue(node.right, scope), json[component], state.file, scope); } } }; };
'use strict'; const expect = require('chai').expect; const deepfind = require('../index'); const simpleFixture = { 'key': 'value' }; const complexFixture = { 'key1': { 'key': 'value1' }, 'key2': { 'key': 'value2' }, 'key3': { 'key': 'value3' } }; describe('deepfind', () => { it('should throw an error when given no object', () => { expect(() => deepfind(null, 'key')).to.throw('deepfind must be supplied an object'); }); it('should throw an error when given no key', () => { expect(() => deepfind({}, null)).to.throw('deepfind must be supplied a key'); }); it('should return an empty array when no key is found', () => { expect(deepfind({}, 'key')).to.be.an.array; expect(deepfind({}, 'key')).to.be.empty; }); it('should return an array when one value matches', () => { expect(deepfind(simpleFixture, 'key')).to.be.an.array; expect(deepfind(simpleFixture, 'key')).to.deep.equal(['value']); }); it('should return an array when multiple values match', () => { expect(deepfind(complexFixture, 'key')).to.be.an.array; expect(deepfind(complexFixture, 'key')).to.deep.equal(['value1', 'value2', 'value3']) }); });
/** * Created by Roman on 16.12.13. */ var moment = require('moment'); function AuthController($scope, $api) { var ctrl = this; $scope.client_id = store.get('client_id'); $scope.api_key = store.get('api_key'); $scope.api_secret = store.get('api_secret'); $scope.err = null; // catch html pieces var $modal = $('#modal-auth').modal({backdrop: true, show: false}); $scope.authenticate_clicked = function(){ NProgress.start(); $scope.err = null; // validate keys and update scopes $api.bitstamp.get_transactions($scope.api_key, $scope.api_secret, $scope.client_id) .success(function(transactions){ $modal.modal('hide'); // save data store.set('client_id', $scope.client_id); store.set('api_key', $scope.api_key); store.set('api_secret', $scope.api_secret); store.set('transactions', transactions); store.set('transactions_updated', moment().unix()); // notify parent that we authenticated $scope.$parent.authenticated(); NProgress.done(); }) .error(function(){ $scope.err = "Failed to verify credentials. Are they correct?"; NProgress.done(); }); }; // init code $('#btn-start').click(function(){ $modal.modal('show'); }); } module.exports = AuthController;