text
stringlengths
2
6.14k
(function (global, factory) { typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global.nearestPeriodicValue = factory(); })(this, function () { "use strict"; /*jshint -W018 */ function nearestPeriodicValue(point, value, period) { var relation = (value - point) / period; // We're equidistant from the nearest point if the // distance from the point is a half-integer value // of our period. var equidistant = !(relation % 0.5) && relation % 1; // If we're equidistant, then we add a period to // ensure that we always pick the value in front var mod = equidistant ? period : 0; // Adjust our value by an amount given by the closest # // of periods contained in the distance between the point // and the value return mod + (value - period * Math.round(relation)); } var nearest_periodic_value = nearestPeriodicValue; return nearest_periodic_value; }); //# sourceMappingURL=./nearest-periodic-value.js.map
exports.User = require('./user') exports.UserFollow = require('./user_follow') exports.Post = require('./post') exports.PostCollection = require('./post_collection') exports.Tag = require('./tag') exports.Message = require('./message') exports.Reply = require('./reply')
var Barc= require ('../lib/barc') fs = require('fs'); generate('defaults', new Barc()); generate('automatic border', new Barc({border:'auto'})); generate('big font', new Barc({fontsize:40})); generate('rotated', new Barc({fontsize:40, border:'auto'}), 45); generate('flipped', new Barc({fontsize:40 }), 90); function generate(title, barc, angle){ var buf = barc.code2of5('1122100017', 300, 200, angle); var filename = 'code2of5-' + title + '.png'; fs.writeFile(__dirname + '/' + filename, buf, function(){ console.log('Created code2of5 and saved it as ', filename); }) }
/* * Copyright (C) 2014 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. All Rights Reserved. */ define([ '../../geom/BoundingBox', '../../util/Color', './KmlElements', './KmlLatLonAltBox', './KmlLod', './KmlObject', './styles/KmlStyle', './util/NodeTransformers', '../../geom/Sector' ], function (BoundingBox, Color, KmlElements, KmlLatLonAltBox, KmlLod, KmlObject, KmlStyle, NodeTransformers, Sector) { "use strict"; /** * Constructs an KmlRegion. Applications usually don't call this constructor. It is called by {@link KmlFile} as * objects from Kml file are read. This object is already concrete implementation. * @alias KmlRegion * @classdesc Contains the data associated with Region node. * @param options {Object} * @param options.objectNode {Node} Node representing region in the document. * @constructor * @throws {ArgumentError} If the node is null or undefined. * @see https://developers.google.com/kml/documentation/kmlreference#region */ var KmlRegion = function (options) { KmlObject.call(this, options); }; KmlRegion.prototype = Object.create(KmlObject.prototype); Object.defineProperties(KmlRegion.prototype, { /** * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. * Default values and required fields are as follows: * @memberof KmlRegion.prototype * @readonly * @type {KmlLatLonBox} */ kmlLatLonAltBox: { get: function () { return this._factory.specific(this, {name: KmlLatLonAltBox.prototype.getTagNames(), transformer: NodeTransformers.kmlObject}); } }, /** * Lod is an abbreviation for Level of Detail. &lt;Lod&gt; describes the size of the projected region on the * screen that is required in order for the region to be considered "active." Also specifies the size of * the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to * transparent). See diagram below for a visual representation of these parameters. * @memberof KmlRegion.prototype * @readonly * @type {KmlLod} */ kmlLod: { get: function () { return this._factory.specific(this, {name: KmlLod.prototype.getTagNames(), transformer: NodeTransformers.kmlObject}); } } }); /** * It tests whether the region intersects the visible area. * @param dc {DrawContext} Frustum to test for intersection. */ KmlRegion.prototype.intersectsVisible = function(dc) { var box = this.kmlLatLonAltBox; var boundingBoxForRegion = new BoundingBox(); boundingBoxForRegion.setToSector(new Sector(box.kmlSouth, box.kmlNorth, box.kmlWest, box.kmlEast), dc.globe, box.kmlMinAltitude, box.kmlMaxAltitude); return boundingBoxForRegion.intersectsFrustum(dc.navigatorState.frustumInModelCoordinates)&& (!box.kmlMinAltitude || dc.eyePosition.altitude > box.kmlMinAltitude) && (!box.kmlMaxAltitude || dc.eyePosition.altitude < box.kmlMaxAltitude); }; /** * @inheritDoc */ KmlRegion.prototype.getTagNames = function () { return ['Region']; }; KmlElements.addKey(KmlRegion.prototype.getTagNames()[0], KmlRegion); return KmlRegion; });
"use strict"; var a = 5; if (a < 3) { console.log(4); }
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema, crypto = require('crypto'); /** * A Validation function for local strategy properties */ var validateLocalStrategyProperty = function(property) { return ((this.provider !== 'local' && !this.updated) || property.length); }; /** * A Validation function for local strategy password */ var validateLocalStrategyPassword = function(password) { return (this.provider !== 'local' || (password && password.length >= 6)); }; /** * User Schema */ var UserSchema = new Schema({ firstName: { type: String, trim: true, default: '', validate: [validateLocalStrategyProperty, 'Please fill in your first name.'] }, lastName: { type: String, trim: true, default: '', validate: [validateLocalStrategyProperty, 'Please fill in your last name.'] }, displayName: { type: String, trim: true }, email: { type: String, trim: true, default: '', validate: [validateLocalStrategyProperty, 'Please fill in your email.'], match: [/.+\@.+\..+/, 'Please fill a valid email address.'] }, username: { type: String, unique: 'This username is already in use.', required: 'Please fill in a username.', trim: true }, password: { type: String, default: '', validate: [validateLocalStrategyPassword, 'Passwords should be at least 6 characters long.'] }, salt: { type: String }, provider: { type: String, required: 'Provider is required.' }, providerData: {}, additionalProvidersData: {}, roles: { type: [{ type: String, enum: ['user', 'admin'] }], default: ['user'] }, updated: { type: Date }, created: { type: Date, default: Date.now }, rating: { type: Number, default: 1500 }, numRatedMatches: { type: Number, default: 0 }, numTotalMatches: { type: Number, default: 0 }, /* For reset password */ resetPasswordToken: { type: String }, resetPasswordExpires: { type: Date } }); /** * Hook a pre save method to hash the password */ UserSchema.pre('save', function(next) { if (this.password && this.password.length >= 6) { this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64'); this.password = this.hashPassword(this.password); } next(); }); /** * Create instance method for hashing a password */ UserSchema.methods.hashPassword = function(password) { if (this.salt && password) { return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64'); } else { return password; } }; /** * Create instance method for authenticating user */ UserSchema.methods.authenticate = function(password) { return this.password === this.hashPassword(password); }; /** * Find possible not used username */ UserSchema.statics.findUniqueUsername = function(username, suffix, callback) { var _this = this; var possibleUsername = username + (suffix || ''); _this.findOne({ username: possibleUsername }, function(err, user) { if (!err) { if (!user) { callback(possibleUsername); } else { return _this.findUniqueUsername(username, (suffix || 0) + 1, callback); } } else { callback(null); } }); }; mongoose.model('User', UserSchema);
// f 模拟替代 first $.fn.ft = function () { return this.equal(0);//沿用我们自定义模拟的equal 代替 eq } console.log($('.eqUl li').ft().html());
module.exports = FieldPacket; function FieldPacket(options) { options = options || {}; this.catalog = options.catalog; this.db = options.db; this.table = options.table; this.orgTable = options.orgTable; this.name = options.name; this.orgName = options.orgName; this.filler1 = undefined; this.charsetNr = options.charsetNr; this.length = options.length; this.type = options.type; this.flags = options.flags; this.decimals = options.decimals; this.filler2 = undefined; this.default = options.default; this.zeroFill = options.zeroFill; this.protocol41 = options.protocol41 } FieldPacket.prototype.parse = function(parser) { if (this.protocol41) { this.catalog = parser.parseLengthCodedString(); this.db = parser.parseLengthCodedString(); this.table = parser.parseLengthCodedString(); this.orgTable = parser.parseLengthCodedString(); this.name = parser.parseLengthCodedString(); this.orgName = parser.parseLengthCodedString(); this.filler1 = parser.parseFiller(1); this.charsetNr = parser.parseUnsignedNumber(2); this.fieldLength = parser.parseUnsignedNumber(4); this.type = parser.parseUnsignedNumber(1); this.flags = parser.parseUnsignedNumber(2); this.decimals = parser.parseUnsignedNumber(1); this.filler2 = parser.parseFiller(2); // parsed flags this.zeroFill = (this.flags & 0x0040 ? true : false); if (parser.reachedPacketEnd()) { return; } this.default = parser.parseLengthCodedNumber(); } else { this.table = parser.parseLengthCodedString(); this.name = parser.parseLengthCodedString(); this.fieldLength = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1)); this.type = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1)); } }; FieldPacket.prototype.write = function(writer) { if (this.protocol41) { writer.writeLengthCodedString(this.catalog); writer.writeLengthCodedString(this.db); writer.writeLengthCodedString(this.table); writer.writeLengthCodedString(this.orgTable); writer.writeLengthCodedString(this.name); writer.writeLengthCodedString(this.orgName); writer.writeFiller(1); writer.writeUnsignedNumber(2, this.charsetNr || 0); writer.writeUnsignedNumber(4, this.fieldLength || 0); writer.writeUnsignedNumber(1, this.type) || 0; writer.writeUnsignedNumber(2, this.flags || 0); writer.writeUnsignedNumber(1, this.decimals || 0); writer.writeFiller(2); if (this.default !== undefined) { writer.writeLengthCodedString(this.default); } } else { writer.writeLengthCodedString(this.table); writer.writeLengthCodedString(this.name); writer.writeUnsignedNumber(1, 0x01); writer.writeUnsignedNumber(1, this.fieldLength); writer.writeUnsignedNumber(1, 0x01); writer.writeUnsignedNumber(1, this.type); } };
/** * Declare some globals * Do NOT touch this file just in case */ module.exports = Object.assign(global, { regeneratorRuntime: require('./vendor/regenerator-runtime'), babelHelpers: require('./vendor/babel-helpers'), _: require('./vendor/underscore'), }); global.pify = require('./lib/wx-pify');
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import ExpansionPanel from '@material-ui/core/ExpansionPanel'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary'; import Typography from '@material-ui/core/Typography'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; const styles = theme => ({ root: { width: '100%', }, heading: { fontSize: theme.typography.pxToRem(15), flexBasis: '33.33%', flexShrink: 0, }, secondaryHeading: { fontSize: theme.typography.pxToRem(15), color: theme.palette.text.secondary, }, }); class ControlledExpansionPanels extends React.Component { state = { expanded: null, }; handleChange = panel => (event, expanded) => { this.setState({ expanded: expanded ? panel : false, }); }; render() { const { classes } = this.props; const { expanded } = this.state; return ( <div className={classes.root}> <ExpansionPanel expanded={expanded === 'panel1'} onChange={this.handleChange('panel1')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>General settings</Typography> <Typography className={classes.secondaryHeading}>I am an expansion panel</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Nulla facilisi. Phasellus sollicitudin nulla et quam mattis feugiat. Aliquam eget maximus est, id dignissim quam. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <ExpansionPanel expanded={expanded === 'panel2'} onChange={this.handleChange('panel2')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>Users</Typography> <Typography className={classes.secondaryHeading}> You are currently not an owner </Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Donec placerat, lectus sed mattis semper, neque lectus feugiat lectus, varius pulvinar diam eros in elit. Pellentesque convallis laoreet laoreet. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <ExpansionPanel expanded={expanded === 'panel3'} onChange={this.handleChange('panel3')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>Advanced settings</Typography> <Typography className={classes.secondaryHeading}> Filtering has been entirely disabled for whole web server </Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Nunc vitae orci ultricies, auctor nunc in, volutpat nisl. Integer sit amet egestas eros, vitae egestas augue. Duis vel est augue. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <ExpansionPanel expanded={expanded === 'panel4'} onChange={this.handleChange('panel4')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>Personal data</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Nunc vitae orci ultricies, auctor nunc in, volutpat nisl. Integer sit amet egestas eros, vitae egestas augue. Duis vel est augue. </Typography> </ExpansionPanelDetails> </ExpansionPanel> </div> ); } } ControlledExpansionPanels.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(ControlledExpansionPanels);
import React from 'react'; class InboxMessage extends React.Component { render() { return ( <div id="message-content"> <p>displaying content of message id: {this.props.params.messageId}</p> </div> ) } } export default InboxMessage;
'use strict'; angular.module('mymtgleagueApp') .controller('NavbarCtrl', function ($scope, $location, Auth) { $scope.menu = [ { 'title': 'Home', 'link': '/' } ]; $scope.isCollapsed = true; $scope.isLoggedIn = Auth.isLoggedIn; $scope.isAdmin = Auth.isAdmin; $scope.getCurrentUser = Auth.getCurrentUser; $scope.logout = function () { Auth.logout(); $location.path('/login'); }; $scope.isActive = function (route) { return route === $location.path(); }; });
/* * Copyright (c) 2012-2016 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ %Include("lib/assert.js"); const globalThis = %GlobalThis(); assertEq(globalThis, this); // 18.3 Constructor Properties of the Global Object assertEq(Array, %Intrinsic("Array")); assertEq(ArrayBuffer, %Intrinsic("ArrayBuffer")); assertEq(Boolean, %Intrinsic("Boolean")); assertEq(DataView, %Intrinsic("DataView")); assertEq(Date, %Intrinsic("Date")); assertEq(Error, %Intrinsic("Error")); assertEq(EvalError, %Intrinsic("EvalError")); assertEq(Float32Array, %Intrinsic("Float32Array")); assertEq(Float64Array, %Intrinsic("Float64Array")); assertEq(Function, %Intrinsic("Function")); assertEq(Int8Array, %Intrinsic("Int8Array")); assertEq(Int16Array, %Intrinsic("Int16Array")); assertEq(Int32Array, %Intrinsic("Int32Array")); assertEq(Map, %Intrinsic("Map")); assertEq(Number, %Intrinsic("Number")); assertEq(Object, %Intrinsic("Object")); assertEq(RangeError, %Intrinsic("RangeError")); assertEq(ReferenceError, %Intrinsic("ReferenceError")); assertEq(RegExp, %Intrinsic("RegExp")); assertEq(Set, %Intrinsic("Set")); assertEq(String, %Intrinsic("String")); assertEq(Symbol, %Intrinsic("Symbol")); assertEq(SyntaxError, %Intrinsic("SyntaxError")); assertEq(TypeError, %Intrinsic("TypeError")); assertEq(Uint8Array, %Intrinsic("Uint8Array")); assertEq(Uint8ClampedArray, %Intrinsic("Uint8ClampedArray")); assertEq(Uint16Array, %Intrinsic("Uint16Array")); assertEq(Uint32Array, %Intrinsic("Uint32Array")); assertEq(URIError, %Intrinsic("URIError")); assertEq(WeakMap, %Intrinsic("WeakMap")); assertEq(WeakSet, %Intrinsic("WeakSet")); // 18.4 Other Properties of the Global Object assertEq(JSON, %Intrinsic("JSON")); assertEq(Math, %Intrinsic("Math")); // TODO: See fixme in proxy.js // assertEq(Proxy, %Intrinsic("Proxy")); assertEq(Reflect, %Intrinsic("Reflect")); assertEq(System, %Intrinsic("System")); // ECMA - 402 assertEq(Intl, %Intrinsic("Intl"));
var files = document.getElementById('include_file'); var add_file_link = '<a href="javascript:void(0)" onclick="add_file_prompt();" id="add_file_link">Add a file</a><br />'; if(files != null) { files.innerHTML = add_file_link; } function file_prompt () { var files_len = files.innerHTML.length; return '<label>(2MB Max)<input type="file" name="file'+files_len+'">' + '<a href="javascript:void(0);" onclick="remove_file_prompt(this);">x</a><br /></label>'; } function add_file_prompt() { files.innerHTML += file_prompt(); if (files.children.length >= 8) document.getElementById('add_file_link').style.visibility = 'hidden'; } function remove_file_prompt(el) { el.parentNode.remove(); if (files.children.length < 8) document.getElementById('add_file_link').style.visibility = ''; }
require('./specs/is-odd.js'); require('./specs/is-even.js');
'use strict'; // Development specific configuration // ================================== module.exports = { pluginStateStore: process.env.KAPTURE_PLUGIN_STORE || '/config/pluginStateStore', settingsFileStore : '/config/system_settings.yml', userSettingDefaults: { rootDownloadPath: process.env.KAPTURE_DOWNLOAD_PATH || '/media', } };
/* *图片操作的controller */ myApp.controller("imgpageCtr",['app','$scope',"restAPI",function(app,$scope,restAPI){ $scope.imgList = []; $scope.unloading = false; //获取图片列表 restAPI.getQiuniuFiles.post({bucketname:"zhugemaolu",limit:10},function(res){ $scope.imgList = res.list; }); $scope.loadStart = function(key){ $scope.unloading = true; } $scope.loadProgress = function(key,per){ $scope.$broadcast("pie",per); } $scope.loadComplete = function(data){ restAPI.getImageUrl.get({key:data.key},function(res){ data.url = res.url; $scope.unloading = false; $scope.imgList.push(data); }); } $scope.deleteList = function(key){ angular.forEach($scope.imgList,function(item,index){ if (item.key==key) { $scope.imgList = app.filter("curArry")($scope.imgList,index); }; }); } }]);
//matiereviewmodel.js // import { Unite } from '../domain/unite'; import { Matiere } from '../domain/matiere'; import { DepartementSigleNameViewModel } from './depsiglenameviewmodel'; // export class MatiereViewModel extends DepartementSigleNameViewModel { constructor(dataservice) { super(dataservice, new Matiere(), 'Matières'); this._unite = new Unite(); this.genres=['pratique','théorie','autre']; } // constructor get genre() { return ((this.current !== undefined) && (this.current !== null)) ? this.current.genre : null; } set genre(s) { if ((this.current !== undefined) && (this.current !== null)) { this.current.genre = s; } } get mat_module() { return ((this.current !== undefined) && (this.current !== null)) ? this.current.mat_module : null; } set mat_module(s) { if ((this.current !== undefined) && (this.current !== null)) { this.current.mat_module = s; } } get coefficient() { return ((this.current !== undefined) && (this.current !== null)) ? this.current.coefficient : null; } set coefficient(v) { if (this.current === null){ return; } let vv = null; if ((v !== undefined) && (v !== null) && (this.current !== null)) { try { let x = parseFloat(v); if ((!isNaN(x)) && (x > 0)) { vv = x; } } catch (e) {} } this.current.coefficient = vv; } get ecs() { return ((this.current !== undefined) && (this.current !== null)) ? this.current.ecs : null; } set ecs(v) { if (this.current === null){ return; } let vv = null; if ((v !== undefined) && (v !== null) && (this.current !== null)) { try { let x = parseFloat(v); if ((!isNaN(x)) && (x > 0)) { vv = x; } } catch (e) {} } this.current.ecs = vv; } get unite() { return ((this._unite !== undefined) && (this._unite !== null) && this._unite.has_id) ? this._unite : null; } set unite(d) { this._unite = ((d !== undefined) && (d !== null) && d.has_id) ? d : null; } get uniteid() { return (this.unite !== null) ? this.unite.id : null; } set uniteid(id) { let vid = ((id !== undefined) && (id !== null) && (id.toString().trim().length > 0)) ? id : null; this.item_model.uniteid = vid; if (vid !== null) { let self = this; this.dataService.get_one_item(new Unite({ _id: vid })).then((d) => { self.unite = d; if ((d !== undefined) && (d !== null) && (d.departementid !== undefined)){ self.departementid = d.departementid; } }); } else { this.unite = null; self.update_title(); self.refreshAll(); } } update_menu() { let mm = []; mm.push({ refer: '#deps', title: 'Départements', desc: 'Départements' }); this.menu = mm; } update_title() { let s = ''; if ((this.baseTitle !== undefined) && (this.baseTitle !== null)) { s = this.baseTitle.trim(); } let u = this.unite; if (u !== null){ s = s + ' / ' + u.sigle; } let d = this.departement; if (d !== null) { s = s + " / " + d.sigle; } this.title = s; } // update_title } // class AnneeViewModel
/** * Given: A sequence of string. * Objective: To find longest subsequence which is palindrome. * Reference: http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/ * Created by gaurav on 6/7/15. */ var sequence = null, subSequence = ''; var findLP = function(i, j, subSequence){ if(i == j){ return sequence[i]; } if( (i==(j+1)) && (sequence[i]!==sequence[j])){ return ""; } if( (i==(j+1)) && (sequence[i]==sequence[j])){ return ""; } if(sequence[i]==sequence[j]){ var f = sequence[i] + findLP(i+1, j-1, subSequence) + sequence[j]; console.log('(%d, %d)\tSubsequence: %s',i,j, f); return f; } if(sequence[i]!==sequence[j]){ var t = findLP(i+1,j, subSequence), t1= findLP(i,j-1, subSequence); console.log('(%d, %d)\tMax of > %s\t%s',i, j, t, t1); return (t.length >= t1.length)?(t):(t1); } }; function find(str){ sequence = str; var start = 0, end = sequence.length -1; return findLP(start, end, ""); } (function(){ console.log(find("GEEKSFORGEEKS")); console.log(subSequence); })();
/** * @class resources * @description 资源模块, 引入其他资源 * @time 2014-12-10 18:13 * @author StarZou **/ (function (window, document) { 'use strict'; var resources = angular.module('resources', ['resources.menus']); })(window, document);
module.exports = function bool_it_up (val) { if (typeof val === 'boolean') { return val } if (typeof val === 'string') { if (/^(true|false)$/i.test(val)) { return val.toLowerCase() === 'true' } if (/^(0|1)$/.test(val)) { return val === '1' } if (/^(y|n)$/i.test(val)) { return val.toLowerCase() === 'y' } if (/^(yes|no)$/i.test(val)) { return val.toLowerCase() === 'yes' } } if (typeof val === 'number') { if (val === -1) { return false } return !!val } if (Array.isArray(val)) { return val.length > 0 } if (typeof val === 'object') { return Object.keys(val).length > 0 } if (Object.prototype.toString.call(val) === '[object Date]') { return !isNaN(val.valueOf()) } return !!val }
module.exports.contains_bad_word = function(given_string) //Returns true if contains bad words , false otherwise { //This array once contained all sorts of profanity //Given that this is an academic project, we did not feel that it was appropriate to include the array of profanity in our final submission var bad_words = ["badword", "bardword1", "badword3"]; for(var x=0;x<bad_words.length;x++) { if(given_string.toLowerCase().indexOf(bad_words[x])>=0) { return true; } } return false; }; module.exports.length_between = function(given_string,min,max) //Returns true if between (inclusive) two ints, false otherwise { if(given_string.length >=min && given_string.length <=max) return true; return false; };
var module = angular.module('app', [ 'ngRoute' ]); /** * Configure routing */ module.config(function($routeProvider) { $routeProvider.when('/', { templateUrl : 'table.html', controller : 'table' }).otherwise('/'); }); /** * Factory to access event resource */ module.factory('EventFactory', function($log, $http, $q){ return { /** * Read all Events */ all:function(){ var deferred = $q.defer(); var promise = deferred.promise; $http.get('resource/events').success(function(data) { $log.info(data); deferred.resolve(data); }) .error(function(error){ $log.error(error); deferred.reject(error); }); return promise; } } }); /** * Service which provides Websocket access */ module.service("MessagingService", function($q, $timeout) { var service = {}, listener = $q.defer(), socket = { client: null, stomp: null }, messageIds = []; service.RECONNECT_TIMEOUT = 30000; service.SOCKET_URL = "/events"; service.CHAT_TOPIC = "/topic/message"; service.CHAT_BROKER = "/app/events"; /** * Exposed receive method */ service.receive = function() { return listener.promise; }; /** * Reconnects if the connection was closed */ var reconnect = function() { $timeout(function() { initialize(); }, this.RECONNECT_TIMEOUT); }; /** * Listener for new messages */ var startListener = function() { socket.stomp.subscribe(service.CHAT_TOPIC, function(data) { var message = JSON.parse(data.body) listener.notify(message); }); }; /** * Initializes the websocket connection. */ var initialize = function() { socket.client = new SockJS(service.SOCKET_URL); socket.stomp = Stomp.over(socket.client); socket.stomp.connect({}, startListener); socket.stomp.onclose = reconnect; }; initialize(); return service; }); /** * Table controller */ module.controller('table', function($scope, EventFactory, MessagingService) { $scope.events = null; $scope.initalLoad = true; $scope.init = function(){ EventFactory.all().then( function(data){ $scope.events=data; }); }; $scope.init(); MessagingService.receive().then(null, null, function(message) { $scope.initalLoad = false; $scope.events.push(message); }); $scope.isLast = function(check){ return (check && !$scope.initalLoad) ? 'danger' : null; } });
'use strict'; //var program = require('commander'); // //program // .version('0.0.1') // .command('jstat', 'Run jstat') // .action(function() { // console.log('hello'); // require('./src/jstat')(); // }); require('./src/jstat');
module.exports = { /** * number | Maxiumum number of files that UploadJs will allow to contain. */ max: Infinity, /** * object: { * key: array * } * defined grouping of file types for allowed_types by MIME type */ types: { images: ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'], }, /** * array | The allowed file types that can be uploaded. Either MIME type of grouping key (see * types) */ allowed_types: ['images'], /** * Http upload options */ upload: { /** * string | The URL that is called when uploading a file */ url: '', /** * string | The name of the parameter that each file is set as in the upload request. */ param: 'file', /** * object | Keyed object of additional parameters to send with the upload request. */ additionalParams: {}, /** * object | Keyed object of additional headers to send with the upload request. */ headers: {}, }, /** * Http delete options */ delete: { /** * string | The URL that is called when deleting a file */ url: '', /** * string | The name of the parameter set with the file id that is set on the deletion request. */ param: 'file', /** * object | Keyed object of additional parameters to send with the delete request. */ additionalParams: {}, /** * object | Keyed object of additional headers to send with the delete request. */ headers: {}, }, };
Module("WAB.controls.NewInstrumentsControl", function (Control) { Control.fn.initialize = function (element) { this.element = element; this.select = this.element.byData("select-new-instrument"); this.element.byData("add-new-instrument").on("click", (function () { WAB.Mediator.trigger("add-new-instrument", [this.select.val()]); }).bind(this)); }; });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.acscDependencies = void 0; var _dependenciesBigNumberClass = require("./dependenciesBigNumberClass.generated"); var _dependenciesComplexClass = require("./dependenciesComplexClass.generated"); var _dependenciesTyped = require("./dependenciesTyped.generated"); var _factoriesAny = require("../../factoriesAny.js"); /** * THIS FILE IS AUTO-GENERATED * DON'T MAKE CHANGES HERE */ var acscDependencies = { BigNumberDependencies: _dependenciesBigNumberClass.BigNumberDependencies, ComplexDependencies: _dependenciesComplexClass.ComplexDependencies, typedDependencies: _dependenciesTyped.typedDependencies, createAcsc: _factoriesAny.createAcsc }; exports.acscDependencies = acscDependencies;
(function () { 'use strict'; var _ = require('lodash'); var Jelps = require('../jelp/jelp.model'); // -------------------------------------------------------------------------------- // Private functions // -------------------------------------------------------------------------------- function errorhandler(err,res) { console.log('Error...: ',err); return res.send(500).json(err); } function callback(res,props,action) { action = _.filter(_.rest(arguments),_.isFunction)[0]; return function(err,found){ if(action){ found = action.apply( action, _.rest(arguments) ); } if(err) { return errorhandler(err,res); } if(!found.length) { return res.send(404); } return res.json(200,_.assign({stream:found},props)); } } function mapDistance(array){ array = _.map(array,function(item){ var newItem = new Jelps(item.obj) newItem.location.dist = item.dis; return newItem; }) return array; } // -------------------------------------------------------------------------------- // Public methods // -------------------------------------------------------------------------------- exports.stream = function(req,res){ Jelps.geoNear( {type : "Point",coordinates : [ Number(req.query.lng), Number(req.query.lat) ]},// Longitude first for GeoJson queries { maxDistance : Number(req.query.range || 10000), spherical : true },// Distance in meters; callback( res,{ id:req.params.id,range:req.query.range },mapDistance ) ); } exports.userStream = function(req,res){ Jelps.find( {'_user.id':req.query.userId}, callback(res,{ id:req.params.id }) ); } }()); //End of closure
// meteorite namespace var Meteorite = Meteorite || {}; // initialize websocket Meteorite.websocket = new WebSocket("ws://" + location.hostname + ":8080/"); console.log('starting meteorite websockets. . .'); // when a new websocket message is received Meteorite.websocket.onmessage = function(msg) { // parse the json message // todo: handle non-json messages var json = JSON.parse(msg.data); // log the data console.log(json); // if this is a delete if (json.bind_data === 'delete') { // remove the item $('#' + json.bind_key).remove(); // halt further processing return false; } // for each meteorite class $('.meteorite').each(function() { // if the bind keys match if ($(this).data('bind-key') === json.bind_key) { console.log('bind found'); // if there is no bind-attr present, this is a collection if ($(this).data('bind-attr') === undefined) { Meteorite.add(json, $(this)); // else update the element } else { Meteorite.update(json, $(this)); } } }); } // add an item Meteorite.add = function(json, $element) { // add to the dom $element.append(json.bind_data); // listen to subscribe events Meteorite.subscribe($(json.bind_data).find('.meteorite').data('bind-key')); } // update a single attribute Meteorite.update = function(json, $element) { // get the bind data var bind_data = JSON.parse(json.bind_data); // desired attribute var bind_attr = $element.data('bind-attr'); // get the attribute data var attr_data = bind_data[bind_attr]; // update the property $element.prop('checked', attr_data); // update the text $element.text(attr_data); // notify event handlers that a change has occurred $element.trigger('change'); } // subscribe to all bind keys of meteorite classes Meteorite.subscribeAll = function() { // for each meteorite class $('.meteorite').each(function() { // if there is a bind key if ($(this).data('bind-key') !== undefined) { // subscribe Meteorite.subscribe($(this).data('bind-key')); } }); } // wait for websocket to be ready, then subscribe all Meteorite.subscribeAfterWebsocket = function() { // set a 5ms timeout setTimeout(function() { // if the websocket is ready if (Meteorite.websocket.readyState === 1) { // send the subscribe notices Meteorite.subscribeAll(); // try again if not ready } else { Meteorite.subscribeAfterWebsocket(); } }, 5); } // subscribe to events when the websocket is ready Meteorite.subscribe = function(bind_key) { // send the subscribe notice Meteorite.websocket.send(JSON.stringify({ action: 'subscribe', key: bind_key })); } // when the document is ready $(document).on('page:load ready', function() { Meteorite.subscribeAfterWebsocket(); });
const Channel = require('../lib/csp/async-channel'); async function sleep(duration) { return new Promise(resolve => setTimeout(resolve, duration)) } async function player(name, table) { while (true) { let ball = await table.take(); if (ball === null) { // closed channel console.log(`${name}: table's gone!`); break; } ball.hits++; console.log(`${name}! Hits: ${ball.hits}`); await sleep(100); try { await table.put(ball); } catch (e) { break; } } } async function pingPong() { console.log('Opening ping-pong channel!'); let table = new Channel(); player('ping', table); player('pong', table); console.log('Serving ball...'); let ball = {hits: 0}; await table.put(ball); await sleep(1000); console.log('Closing ping-pong channel...'); table.close(); // await table.done(); // console.log('Channel is fully closed!'); // console.log(`Ball was hit ${ball.hits} times!`); } pingPong();
/** * Created by lequanghiep on 1/16/2017. */ 'use strict'; angular.module('myApp') .controller('ScoreboardController', function ($scope, API_URL, DataTable) { var loadScoreboardList = function loadScoreboardList() { var options = { url: [API_URL, 'scoreboard/fetch'].join(''), columns: [ {'title': 'ID', 'data': null}, {'title': 'Code', 'data': 'code'}, {'title': 'Status', 'data': 'status'}, {'title': 'Point', 'data': 'point'}, {'title': 'Time', 'data': 'time'} ], columnDefs: [ { "render": function (data) { return [data, 's'].join(''); }, "targets": -1 }, { "render": function (data) { var className = data === 'True' ? 'label-success' : 'label-danger'; return ['<span class="label label-sm ', className, '">', data, '</span>'].join(''); }, "targets": -3 } ] }; options.delete = function (data) { $scope.deleteClass(data); }; options.edit = function (data) { $scope.edit(data); }; DataTable.generateDataTable(options, angular.element(document.querySelector('#scoreboardDataTable'))); }; loadScoreboardList(); });
import React from 'react'; import pace from '../../../public/vendor/pace/pace'; class Progress extends React.Component { componentDidMount() { pace.start(); } render() { return (null) } } export default Progress
import filter from './selection/filter'; import data from './selection/data'; import sort from './selection/sort'; import enter from './selection/enter'; import merge from './selection/merge'; import select from './selection/select'; import attr from './selection/attr'; import tagged from './selection/tagged'; import on from './selection/on'; import append from './selection/append'; import selectAll from './selection/selectAll'; import transition from './selection/transition'; import call from 'd3-selection/src/selection/call'; import nodes from 'd3-selection/src/selection/nodes'; import node from 'd3-selection/src/selection/node'; import size from 'd3-selection/src/selection/size'; import empty from 'd3-selection/src/selection/empty'; import each from 'd3-selection/src/selection/each'; import property from 'd3-selection/src/selection/property'; import datum from 'd3-selection/src/selection/datum'; export default function Selection(groups, parents) { this._groups = groups; this._parents = parents; } Selection.prototype.filter = filter; Selection.prototype.property = property; Selection.prototype.data = data; Selection.prototype.datum = datum; Selection.prototype.call = call; Selection.prototype.sort = sort; Selection.prototype.each = each; Selection.prototype.empty = empty; Selection.prototype.on = on; Selection.prototype.size = size; Selection.prototype.enter = enter; Selection.prototype.merge = merge; Selection.prototype.attr = attr; Selection.prototype.append = append; Selection.prototype.tagged = tagged; Selection.prototype.select = select; Selection.prototype.selectAll = selectAll; Selection.prototype.transition = transition; Selection.prototype.node = node; Selection.prototype.nodes = nodes;
angular .module('openeApp.cases.parties') .factory('partyPermittedRolesService', PartyPermittedRolesService); function PartyPermittedRolesService($http, $q) { var service = { getRoles: getRoles }; return service; function getRoles() { return $http.get("/api/openesdh/party/roles") .then(successOrReject); } function successOrReject(response) { if (response.status && response.status !== 200) { return $q.reject(response); } return response.data; } }
setTimeout(() => { document.getElementById('fade').style.display = 'none' }, 4000) function splitData (rawData) { const data = {} const tickerNames = [] for (let i = 0; i < rawData.length; i++) { const ticker = rawData[i].Ticker if (!data[ticker]) { data[ticker] = { categoryData: [], values: [], volume: [] } tickerNames.push(ticker) } const dateString = rawData[i].Date const pattern = /(\d{4})(\d{2})(\d{2})/ const dateNewType = dateString.replace(pattern, '$1-$2-$3'); data[ticker].categoryData.push(dateNewType) data[ticker].values.push([rawData[i].Open, rawData[i].Close, rawData[i].Low, rawData[i].High]) data[ticker].volume.push(rawData[i].Volume) } return { tickerNames, data } } function constructOption (categoryName, incomingData) { const data = incomingData[categoryName] return { backgroundColor: '#eee', animation: false, legend: { bottom: 10, left: 'center', data: [categoryName] }, tooltip: { trigger: 'axis', axisPointer: { type: 'line' } }, toolbox: { feature: { dataZoom: { yAxisIndex: false }, brush: { type: ['lineX', 'clear'] } } }, grid: [ { left: '10%', right: '8%', height: '50%' }, { left: '10%', right: '8%', top: '63%', height: '16%' } ], xAxis: [ { type: 'category', data: data.categoryData, scale: true, boundaryGap : false, axisLine: {onZero: false}, splitLine: {show: false}, splitNumber: 20, min: 'dataMin', max: 'dataMax' }, { type: 'category', gridIndex: 1, data: data.categoryData, scale: true, boundaryGap : false, axisLine: {onZero: false}, axisTick: {show: false}, splitLine: {show: false}, axisLabel: {show: false}, splitNumber: 20, min: 'dataMin', max: 'dataMax' } ], yAxis: [ { scale: true, splitArea: { show: true } }, { scale: true, gridIndex: 1, splitNumber: 2, axisLabel: {show: false}, axisLine: {show: false}, axisTick: {show: false}, splitLine: {show: false} } ], dataZoom: [ { type: 'inside', xAxisIndex: [0, 1], start: 25, end: 75 }, { show: true, xAxisIndex: [0, 1], type: 'slider', top: '85%', start: 25, end: 75 } ], series: [ { name: categoryName, type: 'candlestick', data: data.values, itemStyle: { normal: { borderColor: null, borderColor0: null } }, tooltip: { formatter: (param) => { let parame = param[0]; return [ 'Date: ' + parame.name + '<hr size=1 style="margin: 3px 0">', 'Open: ' + parame.data[0] + '<br/>', 'Close: ' + parame.data[1] + '<br/>', 'Lowest: ' + parame.data[2] + '<br/>', 'Highest: ' + parame.data[3] + '<br/>' ].join(''); } } }, { name: 'Volumn', type: 'bar', xAxisIndex: 1, yAxisIndex: 1, data: data.volume } ] } } // 基于准备好的dom,初始化echarts实例 const myChart = echarts.init(document.getElementById('main')) $.get('result.json', (rawData) => { const result = splitData(rawData) const data = result.data const tickerNames = result.tickerNames for (let ticker of tickerNames) { const options = constructOption(ticker, data) setTimeout(() => { myChart.setOption(options) }, 8000) } })
/** */ function Flags(_flags) { "use strict"; var _init, _isValidFlag, _convertToBoolean, _setFlagGetterAndSetter, _getFlagValuesFromHash, _internalFlags = {}, _api = this; const REGEXP_HASHFLAG = /flags\[([A-Za-z0-9\-\_\&=]+)]/i; /************************* Validate *************************/ // If: The flags was called as a function and not as a constructor. // Then: Throw an exception and prevent the API from being returned. if (typeof this === "undefined" || typeof this.constructor === "undefined" || this.constructor.name !== "Flags") { throw new SyntaxError(`Flags is not a function, use it as a constructor. Usage: var flags = new Flags({})`); } // If: The flags list is not defined. // Then: Throw an exception and prevent the API from being returned. if (typeof _flags === "undefined") { throw new SyntaxError(`The flags list is not defined. Pass an object to the constructor.`); } // If: The flags list is not an object. // Then: Throw an exception and prevent the API from being returned. if (typeof _flags !== "object" || Object.keys(_flags).length === 0) { throw new SyntaxError(`The flags list must be an object.`); } /************************* Helper Methods *************************/ _init = function () { var key, flagsFromHash; flagsFromHash = _getFlagValuesFromHash(); for (key in _flags) { _setFlagGetterAndSetter(key, flagsFromHash); } }; _setFlagGetterAndSetter = function (key, flags) { var value = (typeof flags[key] === "boolean") ? flags[key] : _flags[key]; if (_isValidFlag(key, value)) { Object.defineProperty(_api, key, { get: () => { return _internalFlags[key]; }, set: val => _internalFlags[key] = _convertToBoolean(val) }); _internalFlags[key] = _convertToBoolean(value); } }; _isValidFlag = function (key, value) { return ( typeof key === "string" && typeof value === "boolean" && key.trim() !== "" ); }; _convertToBoolean = function (value) { var bool; if (typeof value === "boolean") { bool = value; } else if (typeof value === "number") { bool = (value === 1) ? true : false; } else { throw new SyntaxError(); } return bool; }; _getFlagValuesFromHash = function () { var hashFlags = {}, regexpResult; regexpResult = REGEXP_HASHFLAG.exec(location.hash); if (Array.isArray(regexpResult) && regexpResult.length === 2) { regexpResult[1] .split("&") .forEach(flagStr => { var key, value, parts; parts = flagStr.split("="); key = parts[0]; value = (typeof parts[1] === "string") ? parts[1] : true; if (_isValidFlag(key, value)) { hashFlags[key] = value; } }); } return hashFlags; }; /************************* Initialize *************************/ _init(); /************************* Return API *************************/ // Object.seal() allows for the values of the flags to be changed, but not the list itself. return Object.seal(_api); };
'use strict'; // 然后在当前目录下运行 npm i --save egg-mysql // 开启mysql插件 exports.mysql = { enable: true, package: 'egg-mysql', }; // had enabled by egg // exports.static = true;
'use strict' module.exports = [ function arrayGetSetName(req, res, next) { res.header('name', 'array'); next(); }, function arrayGetSetMethod(req, res, next) { res.header('method', 'get'); res.send(200); next(); }];
var Teacher = function(){ this.age = 7; } Teacher.prototype = { name:'zfpx' } var t = new Teacher(); console.log(t.name); t.name = 'zfpx2'; console.log(t.name);
import React from 'react' // import App from './App'; export default class Home extends React.Component { render () { console.log(this.props) return <div className="content"> {this.props.children} </div> } }
"use strict"; var Constants = function() { }; Constants.SIZE = 20; Constants.TOP = 0; Constants.RIGHT = 1; Constants.BOTTOM = 2; Constants.LEFT = 3; Constants.FRONT = 4; Constants.BACK = 5; Constants.HORIZONTAL_DIRECTIONS = [ Constants.FRONT, Constants.RIGHT, Constants.BACK, Constants.LEFT ];
angular.module('angularity') .directive('bodyClasses', function() { return { link: function(scope, element) { var replaceClass = function(newVal, oldVal) { element.removeClass(oldVal); element.addClass(newVal); }; // Page name class scope.$watch('viewCssClass', replaceClass); } } });
'use strict'; const formatters = require('../../lib/formatting').formatters; function testStringFormatter(name, values) { describe(name, function () { let fn = formatters[name]; it('passes through non-string', () => { fn(0).should.equal(0); fn(false).should.equal(false); expect(fn(null)).to.equal(null); expect(fn(undefined)).to.be.undefined; }); Object.keys(values).forEach(input => { let output = values[input]; it('formats "' + input + '"" to "' + output + '"', () => { fn(input).should.equal(output); }); }); }); } describe('Formatters', () => { describe('boolean', () => { it('formats inputs correctly', () => { formatters.boolean(true).should.equal(true); formatters.boolean('true').should.equal(true); formatters.boolean(false).should.equal(false); formatters.boolean('false').should.equal(false); expect(formatters.boolean('other')).to.be.undefined; expect(formatters.boolean(null)).to.be.undefined; expect(formatters.boolean(undefined)).to.be.undefined; expect(formatters.boolean(1234)).to.be.undefined; }); }); testStringFormatter('trim', { 'nospace': 'nospace', ' lspace': 'lspace', 'rspace ': 'rspace', ' mid space ': 'mid space' }); testStringFormatter('uppercase', { 'lowercase': 'LOWERCASE', 'UPPERCASE': 'UPPERCASE', 'MixedCase': 'MIXEDCASE' }); testStringFormatter('lowercase', { 'lowercase': 'lowercase', 'UPPERCASE': 'uppercase', 'MixedCase': 'mixedcase' }); testStringFormatter('removespaces', { 'nospace': 'nospace', ' lspace': 'lspace', 'rspace ': 'rspace', ' mid space ': 'midspace', ' multiple \t spaces ': 'multiplespaces' }); testStringFormatter('singlespaces', { 'nospace': 'nospace', ' lspace': ' lspace', 'rspace ': 'rspace ', ' mid space ': ' mid space ', ' multiple \t spaces ': ' multiple spaces ' }); testStringFormatter('hyphens', { 'nohyphen': 'nohyphen', 'hyphen–one': 'hyphen-one', 'hyphen—two': 'hyphen-two', '-—–—-multiple-—–—-hyphens-—–—-': '-multiple-hyphens-' }); testStringFormatter('apostrophes', { 'no apos': 'no apos', 'normal\'apos': 'normal\'apos', 'curly’apos': 'curly\'apos', 'back`tick': 'back\'tick', 'forward‘apos': 'forward\'apos' }); testStringFormatter('quotes', { 'no quotes': 'no quotes', 'double"quotes': 'double"quotes', 'double“open': 'double"open', 'double”close': 'double"close' }); testStringFormatter('removeroundbrackets', { 'nobrackets': 'nobrackets', '(brackets)': 'brackets' }); testStringFormatter('removehyphens', { 'nohyphen': 'nohyphen', 'hyphen–one': 'hyphenone', 'hyphen—two': 'hyphentwo', '-—–—-multiple-—–—-hyphens-—–—-': 'multiplehyphens' }); testStringFormatter('removeslashes', { 'noslashes': 'noslashes', '/forward/slashes': 'forwardslashes', '\\back\\slashes': 'backslashes' }); testStringFormatter('ukphoneprefix', { '07987654321': '07987654321', '+447987654321': '07987654321', '+4407987654321': '07987654321', '+44(0)7987654321': '07987654321', '+44(07987654321': '07987654321', '+440)7987654321': '07987654321', '+44()7987654321': '07987654321' }); describe('base64decode', () => { it('decodes base64 correctly', () => { formatters.base64decode('YWJjMTIz').should.equal('abc123'); }); }); });
var g_pagerAssessments = null; /** * Modal VIewer **/ var g_assessmentModalWidget = null; function AssessmentModalWidget() { this.composeContent = function(data) { if(data == null || Object.keys(data).length == 0) { alert(ALERTS["no_assessment"]); return; } var assessments = []; for(var key in data) { var assessmentJson = data[key]; var assessment = new Assessment(assessmentJson); assessments.push(assessment); } var ret = $("<div>", { style: "padding: 10%" }).appendTo(par); var tbl = $("<table class='assessments-viewer'>").appendTo(ret); var head = $("<tr class='assessments-viewer-row'>").appendTo(tbl); $('<th>', { text: TITLES["content"], "class": "assessments-viewer-header-content" }).appendTo(head); $('<th>', { text: TITLES["from"], "class": "assessments-viewer-header-from" }).appendTo(head); for(var i = 0; i < assessments.length; i++) { var assessment = assessments[i]; var row = $("<tr class='assessments-viewer-row'>").appendTo(tbl); $('<td>', { text: assessment.content }).appendTo(row); var fromCell = $("<td>").appendTo(row); var iconSlot = $("<img>", { src: assessment.fromPlayer.avatar, "class": "assessments-viewer-avatar" }).appendTo(fromCell); var nameSlot = $("<span>", { text: assessment.fromPlayer.name, "class": "assessments-viewer-name" }).appendTo(fromCell); } }; } AssessmentModalWidget.inherits(BaseModalWidget); function initAssessmentModalWidget(par){ g_assessmentModalWidget = new AssessmentModalWidget(); g_assessmentModalWidget.appendTo(par, false); } function onQueryAssessmentsSuccess(data) { g_assessmentModalWidget.refresh(data); g_assessmentModalWidget.show(); } function onQueryAssessmentsError(err) { } function queryAssessments(refIndex, numItems, direction, to, activityId) { var token = getToken(); if (token == null) { focusLogin(); return; } var params = {}; if(refIndex != null) params[g_keyRefIndex] = refIndex; if(numItems != null) params[g_keyNumItems] = numItems; if(direction != null) params[g_keyDirection] = parseInt(direction); params[g_keyToken] = token; params[g_keyTo] = to; params[g_keyActivityId] = activityId; $.ajax({ type: "GET", url: "/assessment/query", data: params, success: function(data, status, xhr) { onQueryAssessmentsSuccess(data); }, error: function(xhr, status, err) { onQueryAssessmentsError(err); } }); } function queryAssessmentsAndRefresh(to, activityId) { queryAssessments(0, 20, g_directionForward, to, activityId); } /** * Pager Viewer **/ function AssessmentPager(numItemsPerPage, url, paramsGenerator, extraParams, cacheSize, filterMap, onSuccess, onError) { this.init(numItemsPerPage, url, paramsGenerator, extraParams, cacheSize, filterMap, onSuccess, onError); this.updateScreen = function(data) { // TODO: handle the 'page' param if (!data || Object.keys(data).length === 0) return; for (var key in data) { var json = data[key]; var assessment = new Assessment(json); generateAssessmentTag(this.screen, assessment); } }; } AssessmentPager.inherits(Pager); function generateAssessmentTag(par, assessment) { $("<span>", { text: assessment.content, "class": "assessment-tag" }).click(assessment, function(evt) { evt.preventDefault(); var aAssessment = evt.data; window.location.hash = ("detail?" + g_keyActivityId + "=" + aAssessment.activityId); }).appendTo(par); } function onListAssessmentsSuccess(data) { g_pagerAssessments.refreshScreen(data); } function onListAssessmentsError(err) { } function generateAssessmentsListParams(pager, page) { if (page == null) return null; var token = getToken(); if (token == null) { focusLogin(); return; } var params = {}; params[g_keyToken] = token; var pageSt = page - 2; var pageEd = page + 2; var offset = pageSt < 1 ? (pageSt - 1) : 0; pageSt -= offset; pageEd -= offset; params[g_keyPageSt] = pageSt; params[g_keyPageEd] = pageEd; if (pager.nItems != null) params[g_keyNumItems] = pager.nItems; if (g_activityId != null) params[g_keyActivityId] = g_activityId; if (pager.filters != null) { for (var i = 0; i < pager.filters.length; ++i) { var filter = pager.filters[i]; params[filter.key] = filter.selector.val(); } } if (pager.extraParams == null) return params; for (var key in pager.extraParams) { params[key] = pager.extraParams[key]; } return params; } function listAssessments(page, onSuccess, onError) { // prototypes: onSuccess(data), onError(err) var params = generateAssessmentsListParams(g_pagerAssessments, page); $.ajax({ type: "GET", url: "/assessment/list", data: params, success: function(data, status, xhr) { if (isTokenExpired(data)) { logout(null); return; } onSuccess(data); }, error: function(xhr, status, err) { onError(err); } }); } function listAssessmentsAndRefresh() { var page = 1; listAssessments(page, onListAssessmentsSuccess, onListAssessmentsError); }
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var common_1 = require('@angular/common'); var core_1 = require('@angular/core'); var file_drop_directive_1 = require('./file-drop.directive'); var file_select_directive_1 = require('./file-select.directive'); var FileUploadModule = (function () { function FileUploadModule() { } FileUploadModule = __decorate([ core_1.NgModule({ imports: [common_1.CommonModule], declarations: [file_drop_directive_1.FileDropDirective, file_select_directive_1.FileSelectDirective], exports: [file_drop_directive_1.FileDropDirective, file_select_directive_1.FileSelectDirective] }), __metadata('design:paramtypes', []) ], FileUploadModule); return FileUploadModule; }()); exports.FileUploadModule = FileUploadModule;
//This file handles the configuration of the app. //It is required by app.js var express = require('express'); module.exports = function(app, io) { //Set .html as default template extension app.set('view engine', 'html'); //Initialize the ejs template engine app.engine('html', require('ejs').renderFile); //Tell express wherer it can find the templates app.set('views', __dirname + '/views'); //Make the files in public folder available to all user app.use(express.static(__dirname + '/public')); };
angular .module('admin.deals') .component('deals', DealsComponent()) .config(DealsConfig); function DealsComponent() { return { template: '<ui-view autoscroll></ui-view>' }; } function DealsConfig($stateProvider, $urlRouterProvider) { $urlRouterProvider.when("/admin/promoções", "/admin/promoções/lista"); $urlRouterProvider.when("admin.deals", "/admin/promoções/lista"); var state = { abstract: true, name: 'admin.deals', url: '/promoções', component: 'deals' }; $stateProvider.state(state); }
'use strict' // fix for missing phantomjs bind function if (typeof Function.prototype.bind != 'function') { Function.prototype.bind = function bind(obj) { var args = Array.prototype.slice.call(arguments, 1), self = this, nop = function() { }, bound = function() { return self.apply( this instanceof nop ? this : (obj || {}), args.concat( Array.prototype.slice.call(arguments) ) ); }; nop.prototype = this.prototype || {}; bound.prototype = new nop(); return bound; }; } define(['LayoutManager'], function (LayoutManager) { describe('LayoutManager', function () { describe('when instancing a feed', function () { it('should fail if no data', function () { expect(LayoutManager.addFeed).toThrow(new Error('Dataset required')); }); it('should fail if feed is not an array', function () { expect( function () {LayoutManager.addFeed({type: 'text/plain'});} ).toThrow(new Error('Feeds must be of type [Array]')); }); it('should fail if invalid feed type', function () { expect( function () {LayoutManager.addFeed([{type: 'text/plain'}]);} ).toThrow(new Error('Invalid feed parameter: type')); }); it('should generate a new feed in layout', function () { var feedEntity, parentContainer; // create temporary container parentContainer = document.createElement('div') parentContainer.id = LayoutManager.get('container').id; document.body.appendChild(parentContainer); LayoutManager.addFeed([ {type: 'image/jpeg', url: '//localhost/photo_1.jpg'}, {type: 'image/jpeg', url: '//localhost/photo_2.jpg'}, {type: 'image/jpeg', url: '//localhost/photo_3.jpg'}, {type: 'image/jpeg', url: '//localhost/photo_4.jpg'} ]); expect( parentContainer.querySelectorAll('.' + LayoutManager.get('feedClass') + ' img').length ).toBe(4); }); }); }); });
/* eslint-disable no-underscore-dangle */ const Invoker = require('./invoker'); const Server = require('./server'); class Provider { static init(serviceInfo) { if (Provider.instances) { throw new Error(`service ${Invoker.getDescription(serviceInfo)} has been registered`); } Provider.called = true; Provider.instances = new Provider(serviceInfo); return Provider.instances; } constructor(serviceInfo) { this.invoker = Invoker.createInstance(serviceInfo); this.server = Server.createInstance(); } configServer(options) { this.server.config(options); return this; } listen(port) { this.invoker.setPort(port); return this .server .listen(port) .then(() => this.invoker.init()); } addMethods(functions) { const funcNames = Object.keys(functions); if (funcNames.length === 0) { throw new Error('methods should have handlers'); } funcNames.forEach((name) => { this.addMethod(name, functions[name]); }); return this; } addMethod(functionName, handler) { if (!functionName || !handler) { throw new Error('function name or handler should not be empty'); } this.invoker.addMethod(functionName); this.server.addHandler(functionName, handler); return this; } /** * dispose provider * should remove invoker from zookeeper before server closed * @return {Promise.<void>} */ dispose() { return this.invoker.dispose(); } } module.exports = Provider;
/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2021 School of Management and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ /** * @fileoverview * @author Maxence Laurent <maxence.laurent> <gmail.com> */ /* * REGEX * Accent detection : [^\w\s\d\{\}\[\],.%\*\/\(\)<>@.:\"\\=;|\'-+&#] * */ I18n.add("fr" , { wc: "Nombre de mots", cc: "Nombre de signes", data: "Textes", mean: "Moyenne", median: "Médiane", sd: "écart-type", overview: "Aperçu", editionStatus: "Édition", reviewDoneTitle: "Feedbacks terminés", commentsDoneTitle: "Commentaires Terminés", reviewDone: "Terminé", commented: "Terminé", closed: "Terminé", completed: "Terminé", commenting: "En cours", reviewing: "En cours", editing: "En cours", ready: "Terminé", na: "N/A", evicted: "Évincé" });
'use strict'; //TODO - dont close main window chrome.bookmarks.create({ 'title': 'SaveAllTheTabs' }, function (newFolder) { //console.log("added folder: " + newFolder.title); chrome.tabs.query({}, function (t) { t.forEach( function (val, index) { chrome.bookmarks.create({ 'parentId': newFolder.id, 'title': val.title, 'url': val.url }); //console.log(val.title); //console.log(val.url); //put in logic for last tab here chrome.tabs.remove(val.id); } ); chrome.tabs.create({},function(){}); }); });
'use strict'; // Declare app level module which depends on views, and components angular.module('scenarioEditor', [ 'ngRoute', 'scenarioEditor.charView', 'scenarioEditor.lineView', 'scenarioEditor.convoView', 'scenarioEditor.version' ]) .config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/charView'}); }]) .service('charService', function () { var charData = []; var charId = 0; var currChar = 0; return { chars:function () { return charData; }, addChar:function () { charId++; charData.push({'id':charId,'name':'','states':[] }); }, deleteChar:function (character) { charData.splice(charData.indexOf(character),1); }, editChar:function (character) { currChar = character.id; }, getCurrChar:function () { return currChar; }, addStateToChar:function (character,id) { charData[charData.indexOf(character)].states.push({'id':id,'name':'','convoId':0}); }, getStatesLength:function (character) { return charData[charData.indexOf(character)].states.length; } }; }) .service('convoService', function () { var convoData = [ {'id':0,'name':'Conversation 0'} ]; var currConversation = 0; return { conversations:function () { return convoData; }, addConversation:function () { currConversation++; convoData.push({'id':currConversation,'name':'Conversation '+currConversation}); }, editConversation:function (convo) { //TODO: Make this work }, deleteConversation:function (convo) { convoData.splice(convoData.indexOf(convo),1); } }; }) .service('lineService', function () { var lineData = [ {'id':0,'character':'','text':''} ]; var currLine = 0; return { lines:function () { return lineData; }, addLine:function () { currLine++; lineData.push({'id':currLine,'character':'',text:''}); }, deleteLine:function (character) { lineData.splice(lineData.indexOf(character),1); } }; }); var scenarioEditor = angular.module('scenarioEditor'); scenarioEditor.controller('EditorCtrl', ['$scope', '$http', 'convoService', 'charService', 'lineService', function ($scope,$http,convoService,charService,lineService) { // ABSTRACTION LAYER $scope.getChars = function () { return charService.chars(); }; $scope.getConvos = function () { return convoService.conversations(); }; $scope.getLines = function () { return lineService.lines(); }; // CHECK FOR CHANGES $scope.$watch('getChars()', function() { $scope.msg = '*'; $scope.dlVisible = false; }, true); $scope.$watch('getConvos()', function() { $scope.msg = '*'; $scope.dlVisible = false; }, true); $scope.$watch('getLines()', function() { $scope.msg = '*'; $scope.dlVisible = false; }, true); // SAVE JSON FILE $scope.dlVisible = false; $scope.save = function() { $scope.dataObj = { characters : $scope.getChars(), conversations : $scope.getConvos() }; $http.post('postHandler.php', angular.toJson($scope.dataObj)).then(function(data) { $scope.msg = 'Data saved.'; $scope.dlVisible = true; }); $scope.msg2 = 'Data sent: '+ $scope.jsonData; }; } ]);
// checks if the URL is the user's profile page // 'thisPath' = the requested url path following the protocol and hostname function isProfilePage(thisPath) { let userProfileLocation = '/user'; let bool = undefined; thisPath === userProfileLocation ? bool = true : bool = false; return bool; } // checks if the URL is the the page to display an exercise's history // 'thisPath' = the requested url path following the protocol and hostname function isExerciseDetailPage(thisPath) { let exerciseDetailLocation = '/exercise/detail'; let bool = undefined; // remove the exerciseID from the path requested let pathArray = thisPath.split('/'); pathArray.pop(); let path = pathArray.join('/'); path === exerciseDetailLocation ? bool = true : bool = false; return bool; } // checks if the URL is the the page to log a workout // 'thisPath' = the requested url path following the protocol and hostname function isWorkoutLogPage(thisPath) { let workoutLogLocation = '/workout/log'; let bool = undefined; thisPath === workoutLogLocation ? bool = true : bool = false; return bool; } export { isProfilePage, isExerciseDetailPage, isWorkoutLogPage };
var dotnet = require('electron-dotnet'); //var hello = dotnet.func("./src/Emitter/bin/Debug/Emitter.dll"); var hello = dotnet.func("./src/Emitter/Emitter.cs"); //Make method externaly visible this will be referenced in the renderer.js file exports.sayHello = arg => { hello('Emitter', function (error, result) { if (error) throw error; if (result) console.log(result); }); }
import getObjectDiff from './object'; function addDiffIndexPrefix (diff, arrayIndexStr) { //NOTE: add gaps with length equal the length of prefix //'1' => '[0]: 1' //'^' => ' ^' var marker = diff.marker ? arrayIndexStr.replace(/./g, ' ') + diff.marker : ''; diff.expected = arrayIndexStr + diff.expected; diff.actual = arrayIndexStr + diff.actual; diff.marker = marker; } export default function getArraysDiff (err, maxStringLength) { var arrayIndexStr = `[${err.key}]: `; maxStringLength -= arrayIndexStr.length; var diff = getObjectDiff(err, maxStringLength); addDiffIndexPrefix(diff, arrayIndexStr); return diff; }
(function() { var customers = getCustomerList(); // function getCustomerList is in the file datacontext.js var orders = customers.map(function(customer) { return customer.Orders.filter(function(order) { return order.Total >= 2000; }).map(function(order) { return { customerId: customer.CustomerId, orderId: order.OrderId, total: order.Total }; }); }).reduce(function(arr1, arr2) { return arr1.concat(arr2); }, []); orders.forEach(function(order) { console.log("CustomerID=" + order.customerId + " OrderID=" + order.orderId + " Total=" + order.total); }); })();
(function () { 'use strict'; function CommitDetailsCtrl($scope, $routeParams, $location, commits, notifier) { commits.getCommitById($routeParams.id) .then(function (data) { $scope.commit = data; }); } angular.module('sourceControlApp.controllers') .controller('CommitDetailsCtrl', ['$scope', '$routeParams', '$location', 'commits', CommitDetailsCtrl]); }());
(function () { 'use strict'; angular .module('snippets') .run(menuConfig); menuConfig.$inject = ['menuService']; function menuConfig(menuService) { menuService.addMenuItem('topbar', { title: 'Snippets', state: 'snippets', icon: 'mdi mdi-content-save', roles: ['*'] }); } }());
/** * @license Highstock JS v8.1.2 (2020-06-16) * @module highcharts/indicators/accumulation-distribution * @requires highcharts * @requires highcharts/modules/stock * * Indicator series type for Highstock * * (c) 2010-2019 Sebastian Bochan * * License: www.highcharts.com/license */ 'use strict'; import '../../indicators/accumulation-distribution.src.js';
import {inject} from 'aurelia-dependency-injection'; import { Router } from 'aurelia-router'; import ApiKeyService from 'resources/services/api-key-service'; @inject(ApiKeyService) export class ApiKeysIndex { constructor(apiKeyService) { this.apiKeyService = apiKeyService; } async activate() { this.apiKeys = await this.apiKeyService.getAll(); } copyKey(keyIndex) { function selectText(element) { var range = document.createRange(); // Create new range object range.selectNodeContents(element); // Set range to encompass desired element text var selection = window.getSelection(); // Get Selection object from currently user selected text selection.removeAllRanges(); // Unselect any user selected text (if any) selection.addRange(range); // Add range to Selection object to select it } const keyElement = document.getElementsByClassName('w-api-key')[keyIndex] selectText(keyElement); document.execCommand('copy'); } }
/*! * chartjs-adapter-luxon v0.2.0 * https://www.chartjs.org * (c) 2019 Chart.js Contributors * Released under the MIT license */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('chart.js'), require('luxon')) : typeof define === 'function' && define.amd ? define(['chart.js', 'luxon'], factory) : (global = global || self, factory(global.Chart, global.luxon)); }(this, function (chart_js, luxon) { 'use strict'; var FORMATS = { datetime: luxon.DateTime.DATETIME_MED_WITH_SECONDS, millisecond: 'h:mm:ss.SSS a', second: luxon.DateTime.TIME_WITH_SECONDS, minute: luxon.DateTime.TIME_SIMPLE, hour: { hour: 'numeric' }, day: { day: 'numeric', month: 'short' }, week: 'DD', month: { month: 'short', year: 'numeric' }, quarter: "'Q'q - yyyy", year: { year: 'numeric' } }; chart_js._adapters._date.override({ _id: 'luxon', // DEBUG /** * @private */ _create: function(time) { return luxon.DateTime.fromMillis(time, this.options); }, formats: function() { return FORMATS; }, parse: function(value, format) { var options = this.options; if (chart_js.helpers.isNullOrUndef(value)) { return null; } var type = typeof value; if (type === 'number') { value = this._create(value); } else if (type === 'string') { if (typeof format === 'string') { value = luxon.DateTime.fromFormat(value, format, options); } else { value = luxon.DateTime.fromISO(value, options); } } else if (type === 'object') { value = luxon.DateTime.fromObject(value); } else if (value instanceof Date) { value = luxon.DateTime.fromJSDate(value, options); } return value.isValid ? value.valueOf() : null; }, format: function(time, format) { var datetime = this._create(time); return typeof format === 'string' ? datetime.toFormat(format, this.options) : datetime.toLocaleString(format); }, add: function(time, amount, unit) { var args = {}; args[unit] = amount; return this._create(time).plus(args).valueOf(); }, diff: function(max, min, unit) { return this._create(max).diff(this._create(min)).as(unit).valueOf(); }, startOf: function(time, unit, weekday) { if (unit === 'isoWeek') { return this._create(time).isoWeekday(weekday).valueOf(); } return unit ? this._create(time).startOf(unit).valueOf() : time; }, endOf: function(time, unit) { return this._create(time).endOf(unit).valueOf(); } }); }));
/*! * Bootstrap-select v1.13.15 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2020 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); } }(this, function (jQuery) { (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Bitte wählen...', noneResultsText: 'Keine Ergebnisse für {0}', countSelectedText: function (numSelected, numTotal) { return (numSelected == 1) ? '{0} Element ausgewählt' : '{0} Elemente ausgewählt'; }, maxOptionsText: function (numAll, numGroup) { return [ (numAll == 1) ? 'Limit erreicht ({n} Element max.)' : 'Limit erreicht ({n} Elemente max.)', (numGroup == 1) ? 'Gruppen-Limit erreicht ({n} Element max.)' : 'Gruppen-Limit erreicht ({n} Elemente max.)' ]; }, selectAllText: 'Alles auswählen', deselectAllText: 'Nichts auswählen', multipleSeparator: ', ' }; })(jQuery); })); //# sourceMappingURL=defaults-de_DE.js.map
/* * /MathJax-v2/localization/gl/TeX.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ MathJax.Localization.addTranslation("gl","TeX",{version:"2.7.7",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/gl/TeX.js");
import React from 'react'; import {Link} from 'react-router' class LeftNav extends React.Component { render () { return( <div className="left-nav"> <h3>ZSL@{this.props.title}</h3> <Link activeStyle={{color:'teal'}} onlyActiveOnIndex={true} to="/"><span className='glyphicon glyphicon-user'></span><br/>Home</Link> <Link activeStyle={{color:'teal'}} to="/blog"><span className='glyphicon glyphicon-leaf'></span><br/>Blog</Link> <Link activeStyle={{color:'teal'}} to="/work"><span className='glyphicon glyphicon-leaf'></span><br/>Work</Link> <Link activeStyle={{color:'teal'}} to="/about"><span className='glyphicon glyphicon-leaf'></span><br/>About</Link> </div> ) } } export default LeftNav;
jsonp({"cep":"64290000","cidade":"Altos","uf":"PI","estado":"Piau\u00ed"});
jsonp({"cep":"99730000","cidade":"Jacutinga","uf":"RS","estado":"Rio Grande do Sul"});
webhook: function(req, res) { if (req.query['hub.verify_token'] === 'tokentoken') { res.send(req.query['hub.challenge']); } else { res.send('Error, wrong validation token'); } }
const merge = require("webpack-merge"); const common = require("./webpack.common.js"); const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = merge(common, { output: { path: path.resolve(__dirname, "../dist/microfrontend3"), filename: "[name].[chunkhash].js" }, devtool: "source-map", plugins: [ new HtmlWebpackPlugin({ chunks: ["main"], filename: "index.html", template: path.resolve(__dirname, "src/react-app.html"), inject: false }) ] });
/** * Bio component that queries for data * with Gatsby's StaticQuery component * * See: https://www.gatsbyjs.org/docs/static-query/ */ import React from "react" import { StaticQuery, graphql } from "gatsby" import Image from "gatsby-image" import { rhythm } from "../utils/typography" function Bio() { return ( <StaticQuery query={bioQuery} render={data => { const { author, social } = data.site.siteMetadata return ( <div style={{ display: `flex`, marginBottom: rhythm(2.5), }} > <Image fixed={data.avatar.childImageSharp.fixed} alt={author} style={{ marginRight: rhythm(1 / 2), marginBottom: 0, minWidth: 50, borderRadius: `100%`, }} imgStyle={{ borderRadius: `50%`, }} /> <p> I'm <strong>{author}</strong>, a software engineer working in London. This is my tech blog. Find out more about me via {` `} <a href={`https://github.com/${social.github}`}> Github </a>,&nbsp; <a href={`https://stackoverflow.com/users/${social.stackoverflow}`}> Stackoverflow </a>,&nbsp; <a href={`/resume/`}> Resume </a> </p> </div> ) }} /> ) } const bioQuery = graphql` query BioQuery { avatar: file(absolutePath: { regex: "/profile-pic.jpg/" }) { childImageSharp { fixed(width: 50, height: 50) { ...GatsbyImageSharpFixed } } } site { siteMetadata { author social { twitter, github, stackoverflow } } } } ` export default Bio
jsonp({"cep":"64563000","cidade":"Floresta do Piau\u00ed","uf":"PI","estado":"Piau\u00ed"});
/*Subscribe to prompt and tag collections */ Template.random.onCreated( function() { var self = this; self.autorun( function() { self.subscribe('prompts'); self.subscribe('tags'); }); });
#!/usr/bin/env node /* The Cedric's Swiss Knife (CSK) - CSK terminal toolbox test suite Copyright (c) 2009 - 2014 Cédric Ronvel The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict" ; /* jshint unused:false */ var termkit = require( '../lib/termkit.js' ) ; var gpm = require( '../lib/gpm.js' ) ; var handler = gpm.createHandler( { stdin: process.stdin , raw: false , mode: 'motion' /* 'drag' or 'button' */ } ) ; handler.on( 'mouse' , function( name , data ) { console.log( 'Mouse event received:' , name , data ) ; } ) ; setTimeout( function() { process.exit() ; } , 15000 ) ;
define(['angular', './navigation.controller', './navigation.services', 'app/core/core.module', 'Restangular', 'common/config/env.module'], function (angular, controller, services) { 'use strict'; var nav = angular.module('app.common.nav', ['app.core', 'restangular', 'config']); nav.config(function (NavHelperProvider) { NavHelperProvider.addToView('src/common/navigation/navigation.tpl.html'); NavHelperProvider.addControllerUrl('common/navigation/navigation.controller'); }); // controllers nav.controller('NavCtrl', controller.NavCtrl); nav.controller('NavItemCtrl', controller.NavItemCtrl); // services nav.factory('MDSalRestangular', services.MDSalRestangular); return nav; });
function main() { (function () { 'use strict'; $('a.page-scroll').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top - 40 }, 900); return false; } } }); // Show Menu on Book $(window).bind('scroll', function() { var navHeight = $(window).height() - 500; if ($(window).scrollTop() > navHeight) { $('.navbar-default').addClass('on'); } else { $('.navbar-default').removeClass('on'); } }); $('body').scrollspy({ target: '.navbar-default', offset: 80 }); // Hide nav on click $(".navbar-nav li a").click(function (event) { // check if window is small enough so dropdown is created var toggle = $(".navbar-toggle").is(":visible"); if (toggle) { $(".navbar-collapse").collapse('hide'); } }); // Portfolio isotope filter /* $(window).load(function() { var $container = $('.portfolio-items'); $container.isotope({ filter: '*', animationOptions: { duration: 750, easing: 'linear', queue: false } }); $('.cat a').click(function() { $('.cat .active').removeClass('active'); $(this).addClass('active'); var selector = $(this).attr('data-filter'); $container.isotope({ filter: selector, animationOptions: { duration: 750, easing: 'linear', queue: false } }); return false; }); }); // Nivo Lightbox $('.portfolio-item a').nivoLightbox({ effect: 'slideDown', keyboardNav: true, });*/ }()); } main();
'use strict'; angular.module('movies').factory('StatsMovieService', [ function() { var statService = {}; var statistics = {}; var localeOptions = { style: 'currency', currency: 'EUR', minimumFractionDigits: 2, maximumFractionDigits: 2 }; var initStatistics = function () { statistics = { collections: { field: 'COLLECTION_NUMBER', value: 0 }, media: { field: 'MOVIE_NUMBER', value: 0 }, mediaValue: { field: 'TOTAL_VALUE', value: 0 }, missingValue: { field: 'MISSING_VALUE', value: 0 }, headerDone: { field: 'VIEWING_STATISTICS' }, done: { field: 'SEEN_MOVIES', value: 0, popover: 'SEEN_MOVIES' }, notDone: { field: 'UNSEEN_MOVIE', value: 0, popover: 'UNSEEN_MOVIE' }, bought: { field: 'MOVIES_BOUGHT', value: 0, popover: 'MOVIES_BOUGHT' }, toBought: { field: 'MOVIES_TO_BUY', value: 0, popover: 'MOVIES_TO_BUY' }, mediaMissing: { field: 'MISSING_MOVIES', value: 0, popover: 'MISSING_MOVIES' }, totalDuration: { field: 'TOTAL_DURATION', value: 0}, totalSeenDuration: { field: 'TOTAL_SEEN_DURATION', value: 0, popover: 'TOTAL_SEEN_DURATION' }, toWatchDuration: { field: 'LEFT_TO_SEE_DURATION', value: 0, popover: 'LEFT_TO_SEE_DURATION' } }; }; var collectionsRef = []; var movieStatistics = function (movie) { if (movie.collectionName && !collectionsRef.Contains(movie.collectionName)) { collectionsRef.push(movie.collectionName); } if (movie.title) { statistics.media.value += 1; if (movie.seen) { statistics.done.value += 1; statistics.totalSeenDuration.value += movie.duration || 0; } else { statistics.notDone.value += 1; statistics.toWatchDuration.value += movie.duration || 0; } } statistics.totalDuration.value += movie.duration || 0; if (movie.bought && movie.title) { if (movie.price) { statistics.mediaValue.value += parseFloat(movie.price) || 0; } else { statistics.missingValue.value += 1; } statistics.bought.value += 1; } else if (movie.bought === false && movie.title) { statistics.toBought.value += 1; } }; var collectionsStatistics = function (collection) { statistics.mediaMissing.value += collection.missing; angular.forEach(collection.data, function (current) { movieStatistics(current); }); }; // Public API statService.calculate = function (array) { initStatistics(); collectionsRef = []; angular.forEach(array, function (current) { if (current.title) { movieStatistics(current); } else { collectionsStatistics(current); } }); statistics.collections.value = collectionsRef.length; statistics.mediaValue.value = statistics.mediaValue.value.toLocaleString('fr-FR', localeOptions); statistics.done.stats = statistics.media.value !== 0 ? (statistics.done.value * 100 / statistics.media.value).toFixed(2) : (0).toFixed(2); statistics.notDone.stats = statistics.media.value !== 0 ? (statistics.notDone.value * 100 / statistics.media.value).toFixed(2) : (0).toFixed(2); statistics.totalSeenDuration.stats = statistics.media.value !== 0 ? (statistics.totalSeenDuration.value * 100 / statistics.totalDuration.value).toFixed(2) : (0).toFixed(2); statistics.toWatchDuration.stats = statistics.media.value !== 0 ? (statistics.toWatchDuration.value * 100 / statistics.totalDuration.value).toFixed(2) : (0).toFixed(2); if (array && array[0] && array[0].title) { statistics.bought.stats = statistics.media.value !== 0 ? (statistics.bought.value * 100 / statistics.media.value).toFixed(2) : (0).toFixed(2); statistics.toBought.stats = statistics.media.value !== 0 ? (statistics.toBought.value * 100 / statistics.media.value).toFixed(2) : (0).toFixed(2); statistics.mediaMissing = undefined; } else { statistics.bought.stats = statistics.media.value !== 0 ? (statistics.bought.value * 100 / (statistics.bought.value + statistics.mediaMissing.value + statistics.toBought.value)).toFixed(2) : (0).toFixed(2); statistics.toBought.stats = statistics.media.value !== 0 ? (statistics.toBought.value * 100 / (statistics.bought.value + statistics.mediaMissing.value + statistics.toBought.value)).toFixed(2) : (0).toFixed(2); statistics.mediaMissing.stats = statistics.media.value !== 0 ? (statistics.mediaMissing.value * 100 / (statistics.bought.value + statistics.mediaMissing.value + statistics.toBought.value)).toFixed(2) : (0).toFixed(2); } return statistics; }; return statService; } ]);
/*# STRING LENGTH You will often need to know how many characters are in a string. For this you will use the .length property. Here's an example: var example = 'example string'; example.length # NOTE Make sure there is a period between example and length. The above code will return a number for the total number of characters in the string. ## The challenge: Create a file named string-length.js. In that file, create a variable named example. Assign the string 'example string' to the variable example. Use console.log to print the length of the string to the terminal. Check to see if your program is correct by running this command: javascripting verify string-length.js ------------------- » To print these instructions again, run: javascripting print » To execute your program in a test environment, run: javascripting run program.js » To verify your program, run: javascripting verify program.js » For help run: javascripting help */ var example = 'example string' console.log(example.length);
var currentUrl = window.location.pathname; $(document).ready(function() { $('.emma-form-label-required').remove(); headerHeight(); fullScreen(); $('.emma-form-label').addClass('input-label'); $('.emma-form-label').html('EMAIL'); $('img[title]').each(function() { $(this).removeAttr('title'); }); //$('').each(function() { $(this).str.replace('p' , 'div'); }); $('.single-text p').replaceWith(function(){ return $("<div />").append($(this).contents()); }); centerItem(); centerCircle(); //fadeoutCircle(); detectIphone(); detectIpad(); $('.styles-menu').fadeIn('slow'); $('.bgimg').fadeIn('slow'); $('#home-circle').delay(3000).fadeOut('slow'); $('#mobile-tab').toggle(function(){ $('.small-cont').slideToggle('slow'); $('#mobile-tab').css({'background-position-y': -31 +'px'}); }, function(){ $('.small-cont').slideToggle('slow'); $('#mobile-tab').css({'background-position-y': 0 +'%'}); }); $('#call_for_credit p:first-child').html('DOLLAR AMOUNT'); $('#gifts .woocommerce-message .button').html('view cart'); $('.woocommerce-message .button').before('<div class="close" onclick="closeMessage();">X</div>'); $('select option:first-child').each(function() { $(this).html(''); }); $('input[type="radio"]').each(function() { $(this).click(function() { headerHeight(); }); }); homeTagline(); bridalSlider(); }); $(window).resize(function() { fullScreen(); headerHeight(); centerItem(); centerCircle(); homeTagline(); bridalSlider(); }); $(window).load(function() { headerHeight(); bridalSlider(); }); $(document).keydown(function(e){ if (e.keyCode == 39) { $('div.cycloneslider-next').trigger('click'); // $('.big-circle').fadeOut(); } else if (e.keyCode == 37) { $('div.cycloneslider-prev').trigger('click'); // $('.big-circle').fadeOut(); } }); function closeMessage() { $('.woocommerce-message').fadeOut('slow'); } function fullScreen(){ var FullscreenrOptions = { width: 1280, height: 1024, bgID: '.bgimg' }; jQuery.fn.fullscreenr(FullscreenrOptions); } function headerHeight(){ var header = $('#header'), headerHeight = $('#header').height(); windowHeight = $(document).height(); winH = $(window).height(); header.css({'height':windowHeight}); $('.wrapper').css({'height':windowHeight}); $('.home .cycloneslider-slide, .home .cycloneslider-slides, .single .cycloneslider-slide, .single .cycloneslider-slides').css({'height':windowHeight}); // if(winH >= 850){ // $('body').css('overflow', 'hidden'); // } else if (winH < 850){ // $('body').css('overflow-y', 'auto'); // } } function detectIphone() { if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { $('#styles-circle').css('display', 'block'); } else { $('#styles-circle').fadeIn('slow'); $('#styles-circle').delay(3000).fadeOut('slow'); } } function detectIpad() { if((navigator.userAgent.match(/iPad/i))) { $('.styles-menu').remove(); $('#home-circle').css('display' , 'none'); } } function centerItem(){ // contWidth = $('.styles-page').width(); winW = $(window).width(); contW = winW - 280; // var w = contWidth - 175; $('.styles-menu').css({'margin-left': (contW/2) - 139}); if(winW < 770){ $('.styles-menu').css('margin-left', 80); } } $('#select-style').live({ mouseenter: function(){$('.styles-menu-link').css('display', 'block')} // mouseleave: function(){$('.styles-menu-link').css('display', 'none')} }); $('.styles-menu').live({ mouseleave: function(){$('.styles-menu-link').css('display', 'none')} }); function centerCircle(){ windowWidth = $(window).width(); windowHeight = $(window).height(); var w = windowWidth - 280; var newW = (windowWidth/2) - 139; $('.big-circle').css({'left': (w/2) - 139 , 'top':(windowHeight/2) -139}); $('#home-tagline').css({'left': newW}); if(windowWidth < 770){ $('.big-circle').css('left', 80); } } function fadeoutCircle() { $('.cycloneslider-prev').click(function(){$('.big-circle').fadeOut();}); $('.cycloneslider-next').click(function(){$('.big-circle').fadeOut();}); } function homeTagline() { // var W = $('#home .vegas-background').width(); // var realW = W -280; // $('#home-tagline').css({'width': realW}); } function bridalSlider() { // $('#bridal .cycloneslider img').each(function() { // var imgH = $(this).height(); // $('#bridal .cycloneslider-slide').css({'height': imgH}); // $('#bridal .cycloneslider-slides').css({'height': imgH}); // }); }
$(document).ready(function(){ /* ---------- Datable ---------- */ $('.datatable').dataTable({ "sDom": "<'row'<'col-lg-6'l><'col-lg-6'f>r>t<'row'<'col-lg-12'i><'col-lg-12 center'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page" } }); });
<script type="text/javascript"> var now = new Date(); var start = new Date(now.getFullYear(), 0, 0); var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000); var oneDay = 1000 * 60 * 60 * 24; var day = Math.floor(diff / oneDay); console.log('Today is', day); </script>
/*! * Connect * Copyright(c) 2011 TJ Holowaychuk * MIT Licensed */ /** * Module dependencies. */ var cookie = require('cookie'); var http = require('http'); var onHeaders = require('on-headers'); var utils = require('./utils') , res = http.ServerResponse.prototype , addListener = res.addListener , setHeader = res.setHeader; /** * Deprecated proxy for .on('header', ...) */ var attachHeaderListener = utils.deprecate(onHeaders, 'res.on("header"): use on-headers module directly'); // apply only once if (!res._hasConnectPatch) { /** * Provide a public "header sent" flag * until node does. * * @return {Boolean} * @api public */ Object.defineProperty(res, 'headerSent', { configurable: true, enumerable: true, get: utils.deprecate(headersSent, 'res.headerSent: use standard res.headersSent') }); if (!('headersSent' in res)) { /** * Provide the public "header sent" flag * added in node.js 0.10. * * @return {Boolean} * @api public */ Object.defineProperty(res, 'headersSent', { configurable: true, enumerable: true, get: headersSent }); } /** * Set cookie `name` to `val`, with the given `options`. * * Options: * * - `maxAge` max-age in milliseconds, converted to `expires` * - `path` defaults to "/" * * @param {String} name * @param {String} val * @param {Object} options * @api public */ res.cookie = function(name, val, options){ options = utils.merge({}, options); if ('maxAge' in options) { options.expires = new Date(Date.now() + options.maxAge); options.maxAge /= 1000; } if (null == options.path) options.path = '/'; this.setHeader('Set-Cookie', cookie.serialize(name, String(val), options)); }; /** * Append additional header `field` with value `val`. * * @param {String} field * @param {String} val * @api public */ res.appendHeader = function appendHeader(field, val){ var prev = this.getHeader(field); if (!prev) return setHeader.call(this, field, val); // concat the new and prev vals val = Array.isArray(prev) ? prev.concat(val) : Array.isArray(val) ? val.concat(prev) : [prev, val]; return setHeader.call(this, field, val); }; /** * Set header `field` to `val`, special-casing * the `Set-Cookie` field for multiple support. * * @param {String} field * @param {String} val * @api public */ res.setHeader = function(field, val){ var key = field.toLowerCase() , prev; // special-case Set-Cookie if ('set-cookie' == key) return this.appendHeader(field, val); // charset if ('content-type' == key && this.charset) { val += '; charset=' + this.charset; } return setHeader.call(this, field, val); }; /** * Proxy to emit "header" event. */ res.on = function(type, listener){ if (type === 'header') { attachHeaderListener(this, listener); return this; } return addListener.apply(this, arguments); }; res._hasConnectPatch = true; } /** * Determine if headers sent. * * @return {Boolean} * @api private */ function headersSent(){ return Boolean(this._header); }
// Jquery with no conflict jQuery(document).ready(function($) { // Datepicker $('#datepicker').datepicker({ inline: true }); // Clock Start setInterval( function() { var seconds = new Date().getSeconds(); var sdegree = seconds * 6; var srotate = "rotate(" + sdegree + "deg)"; $("#sec").css({"-moz-transform" : srotate, "-webkit-transform" : srotate}); }, 1000 ); setInterval( function() { var hours = new Date().getHours(); var mins = new Date().getMinutes(); var hdegree = hours * 30 + (mins / 2); var hrotate = "rotate(" + hdegree + "deg)"; $("#hour").css({"-moz-transform" : hrotate, "-webkit-transform" : hrotate}); }, 1000 ); setInterval( function() { var mins = new Date().getMinutes(); var mdegree = mins * 6; var mrotate = "rotate(" + mdegree + "deg)"; $("#min").css({"-moz-transform" : mrotate, "-webkit-transform" : mrotate}); }, 1000 ); // Clock END // Sidebar - THONG TIN XA HOI // Add new target for linking pages $("ul.scocialNews li a").attr("target", "_blank"); // END THONG TIN XA HOI // Add class for show button icon in menu $("#main-menu a").each(function() { $this = $(this); $cats ="" if ($this.attr('href').indexOf("category") != -1) { $cats = $this.attr('href').split("category"); } else { $cats = $this.attr('href').split("com/"); } if($cats.length = 2) { // Slug name $cat = $cats[1] if ($cat != null) { $cat = $cat.replace(/\//g, ""); } switch($cat) { case "branch": $this.children('span').addClass("fa-th"); break; case "hiring": $this.children('span').addClass("fa-star"); //CatID: 3: hiring break; case "active-images": $this.children('span').addClass("fa-image"); // CatID: 6 : Hình ảnh hoạt động break; case "contact": $this.children('span').addClass("fa-phone"); // CatID: 11 Liên hệ -contact break; case "aboutus": $this.children('span').addClass("fa-info-circle"); //CatID: 13 About us break; default: $this.children("span").addClass("fa-home"); } } else { $this.children("span").addClass("fa-home"); } }); // End add icon for MENU });
/* * Copyright (C) 2016 Daniel Hsing * 2016 Ben Ockmore * 2016 Max Prettyjohns * 2016 Sean Burke * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import * as bootstrap from 'react-bootstrap'; import PropTypes from 'prop-types'; import React from 'react'; const {Col, Nav, NavItem, Row} = bootstrap; function EditorContainer(props) { const {tabActive, editor, children} = props; return ( <div> <Row> <Col md={12}> {editor.title ? <div> <a href=" " title={editor.title.description} > <h1> {`${editor.title.title} ${editor.name}`} </h1> </a> </div> : <h1> {editor.name} </h1> } </Col> </Row> <Row> <Col md={12}> <Nav bsStyle="tabs"> <NavItem active={tabActive === 0} href={`/editor/${editor.id}`} > Profile </NavItem> <NavItem active={tabActive === 1} href={`/editor/${editor.id}/revisions`} > Revisions </NavItem> <NavItem active={tabActive === 2} href={`/editor/${editor.id}/achievements`} > Achievements </NavItem> <NavItem active={tabActive === 3} href={`/editor/${editor.id}/collections`} > Collections </NavItem> </Nav> </Col> </Row> {children} </div> ); } EditorContainer.displayName = 'EditorContainer'; EditorContainer.propTypes = { children: PropTypes.node.isRequired, editor: PropTypes.shape({ id: PropTypes.number, name: PropTypes.string, title: PropTypes.object }).isRequired, tabActive: PropTypes.number.isRequired }; export default EditorContainer;
Component.bugcraft.skinsStructure.defs[ 'smallturret' ] = { frames: { walk: 1, idle: 1, attackMelee: 1, }, events: { } }
var express = require("express"); var cons = require('consolidate'); var bodyParser = require('body-parser'); var __ = require('underscore'); var cors = require('cors'); var app = express(); app.use(bodyParser.urlencoded({ extended: true })); // support form-encoded bodies (for bearer tokens) app.engine('html', cons.underscore); app.set('view engine', 'html'); app.set('views', 'files/protectedResource'); app.set('json spaces', 4); app.use('/', express.static('files/protectedResource')); app.use(cors()); var resource = { "name": "Protected Resource", "description": "This data has been protected by OAuth 2.0" }; var server = app.listen(9002, 'localhost', function () { var host = server.address().address; var port = server.address().port; console.log('OAuth Resource Server is listening at http://%s:%s', host, port); });
function xmlwriter_flush (xmlwriter, empty) { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brett-zamir.me) // * example 1: var xmlwriter = xmlwriter_open_memory(); // * example 1: xmlwriter_flush(false); // * returns 1: "<root>Here's the buffer...</root>" return xmlwriter.flush(empty); }
// last-child pseudo selector // https://github.com/Modernizr/Modernizr/pull/304 Modernizr.addTest('lastchild', function () { return Modernizr.testStyles("#modernizr div {width:100px} #modernizr :last-child{width:200px;display:block}", function (elem) { return elem.lastChild.offsetWidth > elem.firstChild.offsetWidth; }, 2); });
jQuery(document).ready(function($) { // Your JavaScript goes here function myFunction() { var x = document.getElementById("topnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } } });
angular.module('bhima.controllers') .controller('HolidayManagementController', HolidayManagementController); HolidayManagementController.$inject = [ 'HolidayService', 'ModalService', 'NotifyService', 'uiGridConstants', '$state', ]; /** * Holiday Management Controller * * This controller is about the Holiday management module in the admin zone * It's responsible for creating, editing and updating a Holiday */ function HolidayManagementController(Holidays, ModalService, Notify, uiGridConstants, $state) { var vm = this; // bind methods vm.deleteHoliday = deleteHoliday; vm.editHoliday = editHoliday; vm.toggleFilter = toggleFilter; // global variables vm.gridApi = {}; vm.filterEnabled = false; const gridColumn = [ { field : 'display_name', displayName : 'FORM.LABELS.EMPLOYEE_NAME', headerCellFilter : 'translate', }, { field : 'label', displayName : 'FORM.LABELS.DESIGNATION', headerCellFilter : 'translate', }, { field : 'dateFrom', displayName : 'FORM.LABELS.DATE_FROM', cellFilter : 'date:"mediumDate"', headerCellFilter : 'translate', }, { field : 'dateTo', displayName : 'FORM.LABELS.DATE_TO', cellFilter : 'date:"mediumDate"', headerCellFilter : 'translate', }, { field : 'percentage', displayName : 'FORM.LABELS.PERCENTAGE', headerCellFilter : 'translate', type : 'number', }, { field : 'action', width : 80, displayName : '', cellTemplate : '/modules/holidays/templates/action.tmpl.html', enableSorting : false, enableFiltering : false, }, ]; // options for the UI grid vm.gridOptions = { appScopeProvider : vm, enableColumnMenus : false, fastWatch : true, flatEntityAccess : true, enableSorting : true, onRegisterApi : onRegisterApiFn, columnDefs : gridColumn, }; function onRegisterApiFn(gridApi) { vm.gridApi = gridApi; } function toggleFilter() { vm.filterEnabled = !vm.filterEnabled; vm.gridOptions.enableFiltering = vm.filterEnabled; vm.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN); } function loadHolidays() { vm.loading = true; Holidays.read(null, { detailed : 1 }) .then(function (data) { vm.gridOptions.data = data; }) .catch(Notify.handleError) .finally(function () { vm.loading = false; }); } // switch to delete warning mode function deleteHoliday(title) { ModalService.confirm('FORM.DIALOGS.CONFIRM_DELETE') .then(function (bool) { if (!bool) { return; } Holidays.delete(title.id) .then(function () { Notify.success('FORM.LABELS.DELETED'); loadHolidays(); }) .catch(Notify.handleError); }); } // update an existing Holiday function editHoliday(title) { $state.go('holidays.edit', { id : title.id }); } loadHolidays(); }
/** * Module exports. */ module.exports = exports = gyp /** * Module dependencies. */ var fs = require('graceful-fs') , path = require('path') , nopt = require('nopt') , log = require('npmlog') , child_process = require('child_process') , EE = require('events').EventEmitter , inherits = require('util').inherits , commands = [ // Module build commands 'build' , 'clean' , 'configure' , 'rebuild' // Development Header File management commands , 'install' , 'list' , 'remove' ] , aliases = { 'ls': 'list' , 'rm': 'remove' } // differentiate node-gyp's logs from npm's log.heading = 'gyp' /** * The `gyp` function. */ function gyp () { return new Gyp() } function Gyp () { var self = this // set the dir where node-gyp dev files get installed // TODO: make this *more* configurable? // see: https://github.com/nodejs/node-gyp/issues/21 var homeDir = process.env.HOME || process.env.USERPROFILE if (!homeDir) { throw new Error( "node-gyp requires that the user's home directory is specified " + "in either of the environmental variables HOME or USERPROFILE" ); } this.devDir = path.resolve(homeDir, '.node-gyp') this.commands = {} commands.forEach(function (command) { self.commands[command] = function (argv, callback) { log.verbose('command', command, argv) return require('./' + command)(self, argv, callback) } }) } inherits(Gyp, EE) exports.Gyp = Gyp var proto = Gyp.prototype /** * Export the contents of the package.json. */ proto.package = require('../package') /** * nopt configuration definitions */ proto.configDefs = { help: Boolean // everywhere , arch: String // 'configure' , cafile: String // 'install' , debug: Boolean // 'build' , directory: String // bin , make: String // 'build' , msvs_version: String // 'configure' , ensure: Boolean // 'install' , solution: String // 'build' (windows only) , proxy: String // 'install' , nodedir: String // 'configure' , loglevel: String // everywhere , python: String // 'configure' , 'dist-url': String // 'install' , 'tarball': String // 'install' , jobs: String // 'build' , thin: String // 'configure' } /** * nopt shorthands */ proto.shorthands = { release: '--no-debug' , C: '--directory' , debug: '--debug' , j: '--jobs' , silly: '--loglevel=silly' , verbose: '--loglevel=verbose' } /** * expose the command aliases for the bin file to use. */ proto.aliases = aliases /** * Parses the given argv array and sets the 'opts', * 'argv' and 'command' properties. */ proto.parseArgv = function parseOpts (argv) { this.opts = nopt(this.configDefs, this.shorthands, argv) this.argv = this.opts.argv.remain.slice() var commands = this.todo = [] // create a copy of the argv array with aliases mapped argv = this.argv.map(function (arg) { // is this an alias? if (arg in this.aliases) { arg = this.aliases[arg] } return arg }, this) // process the mapped args into "command" objects ("name" and "args" props) argv.slice().forEach(function (arg) { if (arg in this.commands) { var args = argv.splice(0, argv.indexOf(arg)) argv.shift() if (commands.length > 0) { commands[commands.length - 1].args = args } commands.push({ name: arg, args: [] }) } }, this) if (commands.length > 0) { commands[commands.length - 1].args = argv.splice(0) } // support for inheriting config env variables from npm var npm_config_prefix = 'npm_config_' Object.keys(process.env).forEach(function (name) { if (name.indexOf(npm_config_prefix) !== 0) return var val = process.env[name] if (name === npm_config_prefix + 'loglevel') { log.level = val } else { // add the user-defined options to the config name = name.substring(npm_config_prefix.length) // gyp@741b7f1 enters an infinite loop when it encounters // zero-length options so ensure those don't get through. if (name) this.opts[name] = val } }, this) if (this.opts.loglevel) { log.level = this.opts.loglevel } log.resume() } /** * Spawns a child process and emits a 'spawn' event. */ proto.spawn = function spawn (command, args, opts) { if (!opts) opts = {} if (!opts.silent && !opts.stdio) { opts.stdio = [ 0, 1, 2 ] } var cp = child_process.spawn(command, args, opts) log.info('spawn', command) log.info('spawn args', args) return cp } /** * Returns the usage instructions for node-gyp. */ proto.usage = function usage () { var str = [ '' , ' Usage: node-gyp <command> [options]' , '' , ' where <command> is one of:' , commands.map(function (c) { return ' - ' + c + ' - ' + require('./' + c).usage }).join('\n') , '' , 'node-gyp@' + this.version + ' ' + path.resolve(__dirname, '..') , 'node@' + process.versions.node ].join('\n') return str } /** * Version number getter. */ Object.defineProperty(proto, 'version', { get: function () { return this.package.version } , enumerable: true })
import path from 'path'; const kbnDir = path.resolve(__dirname, '../../../../'); export default { rootDir: path.resolve(__dirname, '../..'), roots: [ '<rootDir>/public', '<rootDir>/server' ], modulePaths: [ `${kbnDir}/node_modules` ], collectCoverageFrom: [ `${kbnDir}/packages/kbn-ui-framework/src/components/**/*.js`, `${kbnDir}/!packages/kbn-ui-framework/src/components/index.js`, `${kbnDir}/!packages/kbn-ui-framework/src/components/**/*/index.js`, `${kbnDir}/packages/kbn-ui-framework/src/services/**/*.js`, `${kbnDir}/!packages/kbn-ui-framework/src/services/index.js`, `${kbnDir}/!packages/kbn-ui-framework/src/services/**/*/index.js`, ], moduleNameMapper: { '^ui/(.*)': `${kbnDir}/src/ui/public/$1`, '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': `${kbnDir}/src/dev/jest/mocks/file_mock.js`, '\\.(css|less|scss)$': `${kbnDir}/src/dev/jest/mocks/style_mock.js`, }, setupFiles: [ `${kbnDir}/src/dev/jest/setup/babel_polyfill.js`, `${kbnDir}/src/dev/jest/setup/enzyme.js`, ], coverageDirectory: `${kbnDir}/target/jest-coverage`, coverageReporters: [ 'html', ], globals: { 'ts-jest': { skipBabel: true, }, }, moduleFileExtensions: [ 'js', 'json', 'ts', 'tsx', ], modulePathIgnorePatterns: [ '__fixtures__/', 'target/', ], testMatch: [ '**/*.test.{js,ts,tsx}' ], transform: { '^.+\\.js$': `${kbnDir}/src/dev/jest/babel_transform.js`, '^.+\\.tsx?$': `${kbnDir}/src/dev/jest/babel_transform.js`, }, transformIgnorePatterns: [ '[/\\\\]node_modules[/\\\\].+\\.js$', ], snapshotSerializers: [ `${kbnDir}/node_modules/enzyme-to-json/serializer`, ], reporters: [ 'default', `${kbnDir}/src/dev/jest/junit_reporter.js`, ], };
function Promise() { var thens = []; var that = this; that.then = function(cb) { var p = new Promise(); thens.push(function(val) { p.resolve(cb(val)); }); return p; }; that.resolve = function(val) { var i = 0; for (i = 0; i < thens.length; i++) { thens[i](val); } that.then = function(cb) { var p = new Promise(); p.resolve(cb(val)); return p; }; }; };
app.controller("DeleteCardController", function($scope, FlashCardsFactory, $state) { $scope.deleteCard = function(card) { FlashCardsFactory.removeCard($scope.card).then(function(data) { FlashCardsFactory.deletedCard = true; $state.go('home'); }); }; if (confirm("Are you sure you want to delete this card?")) { console.log($scope.card); $scope.deleteCard($scope.card); } else { return; } });
import { includes } from 'lodash'; import getSiteSetting from 'calypso/state/selectors/get-site-setting'; /** * Check if an email address is disallowed according to * the list of blocked addresses for the site. * * @param {object} state Global state tree * @param {number} siteId Site ID * @param {string} email An email address. * @returns {boolean} If the email address is disallowed. */ export const isAuthorsEmailBlocked = ( state, siteId, email = '' ) => { const blocklist = getSiteSetting( state, siteId, 'disallowed_keys' ) || ''; return includes( blocklist.split( '\n' ), email ); }; export default isAuthorsEmailBlocked;
jQuery( document ).ready(function() { // hide the bottom buy links if the excerpt is closed if (jQuery('.mbm-book-excerpt-read-more').is(":visible")) { jQuery('#mbm-book-links2').hide(); } // handle the editions hide/show jQuery('.mbm-book-editions-toggle').on('click', function() { jQuery(this).siblings('.mbm-book-editions-subinfo').toggle(); jQuery(this).toggleClass('mbm-book-editions-open'); }); // open the excerpt jQuery('.mbm-book-excerpt-read-more').on( 'click', function() { jQuery(this).siblings('.mbm-book-excerpt-text-hidden').toggle(); jQuery(this).toggle(); jQuery('#mbm-book-links2').show(); }); // close the excerpt jQuery('.mbm-book-excerpt-collapse').on( 'click', function() { jQuery(this).parent().toggle(); jQuery(this).parent().siblings('.mbm-book-excerpt-read-more').toggle(); jQuery('#mbm-book-links2').hide(); jQuery('html, body').animate({ scrollTop: (jQuery('.mbm-book-excerpt-read-more').offset().top - 100) },500); }); }); // ready
tinyMCE.addI18n('pt.autosave',{ restore_content: "Restaurar conteúdo salvo automáticament", warning_message: ""Se você restaurar o conteúdo gravado, você vai perder todo o conteúdo que está atualmente no editor.\n\nVocê tem certeza de que deseja restaurar o conteúdo salvo?" });
/** * Created by xykong on 2014/7/15. */ var protobuf = require('pomelo-protobuf'); var util = require('pomelo-protobuf/lib/util'); var should = require('should'); var tc = require('./testMsg'); describe('msgEncoderTest', function () { var protos = protobuf.parse(require('./example.json')); protobuf.init({encoderProtos: protos, decoderProtos: protos}); describe('encodeTest', function () { for (var route in tc) { var msg = tc[route]; var buffer = protobuf.encode(route, msg); console.log(msg); console.log(buffer.length); console.log(buffer) var decodeMsg = protobuf.decode(route, buffer); console.log(decodeMsg); util.equal(msg, decodeMsg).should.equal(true); } }); });
(function() { 'use strict'; /** * @name config * @description config block */ function config($stateProvider) { $stateProvider .state('root.sub-bar-professors.professors', { url: '/professors', templateUrl: 'src/app/professors/professors.tpl.html', controller: 'ProfessorsCtrl as professors' } ); } /** * @name ProfessorsCtrl * @description Controller */ function ProfessorsCtrl(ProfessorsService , $scope) { var professors = this; var postInit = function(professorsData) { professors.professors = professorsData; professors.loaded = true; professors.inputText = 'enter a professor\'s name...'; $scope.$applyAsync(); }; var init = function(){ ProfessorsService.getProfessors(postInit); professors.selectedProf = undefined; professors.loaded = false; professors.inputText = 'loading data...'; professors.orderByDate = function(index) { var stringDate = professors.selectedProf.reviews[index].createDate; return new Date(stringDate); }; }; init(); } angular.module('professors', []) .config(config) .controller('ProfessorsCtrl', ProfessorsCtrl); })();
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('gradientsApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
/*----------------------------------------------------------- * Story的儲存結構 -------------------------------------------------------------*/ var releaseStoryStore = new Ext.data.Store({ fields: [ {name: 'Id', type: 'int'}, {name: 'Link'}, {name: 'Tag'}, {name: 'Name'}, {name: 'Value',type: 'int'}, {name: 'Importance', type: 'int'}, {name: 'Estimation', type: 'float'}, {name: 'Status'}, {name: 'Release'}, {name: 'Sprint'}, {name: 'Notes'}, {name: 'HowToDemo'} ], reader: myReader }); var Sprint_release = Ext.data.Record.create([ {name:'Id', sortType:'asInt'}, 'Goal', 'StartDate', 'Interval', 'Members', 'AvaliableDays', 'FocusFactor', 'DailyScrum', 'DemoDate', 'DemoPlace', 'Check' ]); var SprintReader_release = new Ext.data.XmlReader({ record: 'Sprint', idPath : 'Id', successProperty: 'Result', totalProperty:"StoryPoint" }, Sprint_release); var createSprintStore_release = new Ext.data.Store({ id : 'createSprintStore_release', fields : [{ name : 'Id', type : 'int' }, { name : 'Goal' }, { name : 'StartDate' }, { name : 'Interval' }, { name : 'Members' }, { name : 'AvaliableDays' }, { name : 'FocusFactor' }, { name : 'DailyScrum' }, { name : 'DemoDate' }, { name : 'DemoPlace' }], reader : SprintReader_release }); /* * 提供給Release List的欄位內容 */ var releaseColumns = [{ header: 'ID', dataIndex: 'ID', width: 150, align: 'center' }, { header: 'Name', dataIndex: 'Name', width: 250, align: 'left' }, { header: 'Start Date', width: 150, dataIndex: 'StartDate', align: 'center' }, { header: 'End Date', width: 150, dataIndex: 'EndDate', align: 'center' }, { header: 'Description', width: 250, dataIndex: 'Description', align: 'center' }]; var createReleaseStoryCloumns = function () { var columns = [ { dataIndex: 'Id', header: 'ID', width: 50, /*renderer: makeIssueDetailUrl*/ }, // makeIssueDetailUrl function in IssueGridPanelSupport.js { dataIndex: 'Tag', header: 'Tag', width: 90}, { dataIndex: 'Name', header: 'Story Name', width: 400}, { dataIndex: 'Value', header: 'Value', width: 90}, { dataIndex: 'Estimation', header: 'Estimation', width: 90}, { dataIndex: 'Importance', header: 'Importance', width: 90}, { dataIndex: 'Status', header: 'Status', width: 90}, { dataIndex: 'Release', header: 'Release Id', width: 90 }, { dataIndex: 'Sprint', header: 'Sprint Id', width: 90} ]; return new Ext.grid.ColumnModel({ columns: columns, defaults: { sortable: true } }); }; /* =================================== * Show Release Backlog *==================================*/ var pageSize_ReleaseBacklog = 15; var ReleaseBacklogStoryStore = new Ext.data.Store({ fields: [ {name: 'Id', type: 'int'}, {name: 'Link'}, {name: 'Tag'}, {name: 'Name'}, {name: 'Value',type: 'int'}, {name: 'Importance', type: 'int'}, {name: 'Estimation', type: 'float'}, {name: 'Status'}, {name: 'Release'}, {name: 'Sprint'}, {name: 'Notes'}, {name: 'HowToDemo'} ], reader: myReader, proxy: new Ext.ux.data.PagingMemoryProxy(null,ReleasebacklogGridFilter) }); var ReleaseBacklogColumns = function () { var columns = [{ dataIndex: 'Id', header: 'Story ID', width: 60 },{ dataIndex: 'Name', header: 'Story Name', width: 325 },{ dataIndex: 'Importance', header: 'Importance', width: 80 },{ dataIndex: 'Sprint', header: 'Sprint ID', width: 65 },{ dataIndex: 'Estimation', header: 'Estimation', width: 80 },{ dataIndex: 'Status', header: 'Status', width: 70 }]; return new Ext.grid.ColumnModel({ columns: columns, defaults: { sortable: true } }); }; //Filter var ReleasebacklogGridFilter = new Ext.ux.grid.GridFilters({ local:false, filters: [{ type: 'numeric', dataIndex: 'Id' },{ type: 'list', dataIndex: 'Status', options: ['new', 'closed'] }] }); var ReleaseBacklogGridExpander = new Ext.ux.grid.RowExpander({ tpl : new Ext.XTemplate( '<br><p><b>Name:</b><br /> {Name:nl2br}</p>', '<tpl if="Value"><p><b>Value:</b><br /> {Value:nl2br}</p></tpl>', '<tpl if="Notes"><p><b>Notes:</b><br /> {Notes:nl2br}</p></tpl>', '<tpl if="HowToDemo"><p><b>How To Demo:</b><br /> {HowToDemo:nl2br}</p></tpl>', '<br />' ), enableCaching :false });
define(['proscenium'], function (Proscenium) { return { curtains: ['splash'], prep: function () { var $splash = $(Proscenium.curtains.splash.element); $splash.show(); } }; });