id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
9,400
serverless/serverless-kubeless
lib/deploy.js
handleMQTDeployment
function handleMQTDeployment(trigger, name, namespace, options) { let mqTrigger = trigger; // If only a string is passed, expect it to be the subject if (typeof mqTrigger === 'string') { // Defaults to Kafka mqTrigger = { queue: 'kafka', topic: mqTrigger, }; } else { // Otherwise expect type and subject to be set if (_.isEmpty(mqTrigger.queue)) { throw new Error('You should specify a queue for the trigger event (i.e. kafka, nats)'); } if (_.isEmpty(mqTrigger.topic)) { throw new Error('You should specify a topic for the trigger event'); } } return deployMQTrigger( MQTypes[mqTrigger.queue.toLowerCase()], name, namespace, mqTrigger.topic, { log: options.log } ); }
javascript
function handleMQTDeployment(trigger, name, namespace, options) { let mqTrigger = trigger; // If only a string is passed, expect it to be the subject if (typeof mqTrigger === 'string') { // Defaults to Kafka mqTrigger = { queue: 'kafka', topic: mqTrigger, }; } else { // Otherwise expect type and subject to be set if (_.isEmpty(mqTrigger.queue)) { throw new Error('You should specify a queue for the trigger event (i.e. kafka, nats)'); } if (_.isEmpty(mqTrigger.topic)) { throw new Error('You should specify a topic for the trigger event'); } } return deployMQTrigger( MQTypes[mqTrigger.queue.toLowerCase()], name, namespace, mqTrigger.topic, { log: options.log } ); }
[ "function", "handleMQTDeployment", "(", "trigger", ",", "name", ",", "namespace", ",", "options", ")", "{", "let", "mqTrigger", "=", "trigger", ";", "// If only a string is passed, expect it to be the subject", "if", "(", "typeof", "mqTrigger", "===", "'string'", ")", "{", "// Defaults to Kafka", "mqTrigger", "=", "{", "queue", ":", "'kafka'", ",", "topic", ":", "mqTrigger", ",", "}", ";", "}", "else", "{", "// Otherwise expect type and subject to be set", "if", "(", "_", ".", "isEmpty", "(", "mqTrigger", ".", "queue", ")", ")", "{", "throw", "new", "Error", "(", "'You should specify a queue for the trigger event (i.e. kafka, nats)'", ")", ";", "}", "if", "(", "_", ".", "isEmpty", "(", "mqTrigger", ".", "topic", ")", ")", "{", "throw", "new", "Error", "(", "'You should specify a topic for the trigger event'", ")", ";", "}", "}", "return", "deployMQTrigger", "(", "MQTypes", "[", "mqTrigger", ".", "queue", ".", "toLowerCase", "(", ")", "]", ",", "name", ",", "namespace", ",", "mqTrigger", ".", "topic", ",", "{", "log", ":", "options", ".", "log", "}", ")", ";", "}" ]
Handle message queue trigger input to normalize the users input values. @param {string|object} trigger @param {string} name @param {string} namespace @param {object} options
[ "Handle", "message", "queue", "trigger", "input", "to", "normalize", "the", "users", "input", "values", "." ]
b85b77f584139a8d53f06346b3036f8b3017c9f9
https://github.com/serverless/serverless-kubeless/blob/b85b77f584139a8d53f06346b3036f8b3017c9f9/lib/deploy.js#L476-L502
9,401
fergiemcdowall/search-index
demo/search-app.js
function (elements) { elements.forEach(function(element) { document.getElementById(element).innerHTML = '' document.getElementById(element).value = '' }) }
javascript
function (elements) { elements.forEach(function(element) { document.getElementById(element).innerHTML = '' document.getElementById(element).value = '' }) }
[ "function", "(", "elements", ")", "{", "elements", ".", "forEach", "(", "function", "(", "element", ")", "{", "document", ".", "getElementById", "(", "element", ")", ".", "innerHTML", "=", "''", "document", ".", "getElementById", "(", "element", ")", ".", "value", "=", "''", "}", ")", "}" ]
Empty HTML elements
[ "Empty", "HTML", "elements" ]
f69d992dd4c2a01c84b01feb0e6e57d91b6d7241
https://github.com/fergiemcdowall/search-index/blob/f69d992dd4c2a01c84b01feb0e6e57d91b6d7241/demo/search-app.js#L49-L54
9,402
angular-ui/ui-calendar
src/calendar.js
function (newTokens, oldTokens) { var i; var token; var replacedTokens = {}; var removedTokens = subtractAsSets(oldTokens, newTokens); for (i = 0; i < removedTokens.length; i++) { var removedToken = removedTokens[i]; var el = map[removedToken]; delete map[removedToken]; var newToken = tokenFn(el); // if the element wasn't removed but simply got a new token, its old token will be different from the current one if (newToken === removedToken) { self.onRemoved(el); } else { replacedTokens[newToken] = removedToken; self.onChanged(el); } } var addedTokens = subtractAsSets(newTokens, oldTokens); for (i = 0; i < addedTokens.length; i++) { token = addedTokens[i]; if (!replacedTokens[token]) { self.onAdded(map[token]); } } }
javascript
function (newTokens, oldTokens) { var i; var token; var replacedTokens = {}; var removedTokens = subtractAsSets(oldTokens, newTokens); for (i = 0; i < removedTokens.length; i++) { var removedToken = removedTokens[i]; var el = map[removedToken]; delete map[removedToken]; var newToken = tokenFn(el); // if the element wasn't removed but simply got a new token, its old token will be different from the current one if (newToken === removedToken) { self.onRemoved(el); } else { replacedTokens[newToken] = removedToken; self.onChanged(el); } } var addedTokens = subtractAsSets(newTokens, oldTokens); for (i = 0; i < addedTokens.length; i++) { token = addedTokens[i]; if (!replacedTokens[token]) { self.onAdded(map[token]); } } }
[ "function", "(", "newTokens", ",", "oldTokens", ")", "{", "var", "i", ";", "var", "token", ";", "var", "replacedTokens", "=", "{", "}", ";", "var", "removedTokens", "=", "subtractAsSets", "(", "oldTokens", ",", "newTokens", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "removedTokens", ".", "length", ";", "i", "++", ")", "{", "var", "removedToken", "=", "removedTokens", "[", "i", "]", ";", "var", "el", "=", "map", "[", "removedToken", "]", ";", "delete", "map", "[", "removedToken", "]", ";", "var", "newToken", "=", "tokenFn", "(", "el", ")", ";", "// if the element wasn't removed but simply got a new token, its old token will be different from the current one", "if", "(", "newToken", "===", "removedToken", ")", "{", "self", ".", "onRemoved", "(", "el", ")", ";", "}", "else", "{", "replacedTokens", "[", "newToken", "]", "=", "removedToken", ";", "self", ".", "onChanged", "(", "el", ")", ";", "}", "}", "var", "addedTokens", "=", "subtractAsSets", "(", "newTokens", ",", "oldTokens", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "addedTokens", ".", "length", ";", "i", "++", ")", "{", "token", "=", "addedTokens", "[", "i", "]", ";", "if", "(", "!", "replacedTokens", "[", "token", "]", ")", "{", "self", ".", "onAdded", "(", "map", "[", "token", "]", ")", ";", "}", "}", "}" ]
Compare newTokens to oldTokens and call onAdded, onRemoved, and onChanged handlers for each affected event respectively.
[ "Compare", "newTokens", "to", "oldTokens", "and", "call", "onAdded", "onRemoved", "and", "onChanged", "handlers", "for", "each", "affected", "event", "respectively", "." ]
ac7a76c678a4eb8242a695d0ce133757345e6c31
https://github.com/angular-ui/ui-calendar/blob/ac7a76c678a4eb8242a695d0ce133757345e6c31/src/calendar.js#L146-L172
9,403
angular-ui/ui-calendar
src/calendar.js
function (data) { // convert {0: "Jan", 1: "Feb", ...} to ["Jan", "Feb", ...] return (Object.keys(data) || []).reduce( function (rslt, el) { rslt.push(data[el]); return rslt; }, [] ); }
javascript
function (data) { // convert {0: "Jan", 1: "Feb", ...} to ["Jan", "Feb", ...] return (Object.keys(data) || []).reduce( function (rslt, el) { rslt.push(data[el]); return rslt; }, [] ); }
[ "function", "(", "data", ")", "{", "// convert {0: \"Jan\", 1: \"Feb\", ...} to [\"Jan\", \"Feb\", ...]", "return", "(", "Object", ".", "keys", "(", "data", ")", "||", "[", "]", ")", ".", "reduce", "(", "function", "(", "rslt", ",", "el", ")", "{", "rslt", ".", "push", "(", "data", "[", "el", "]", ")", ";", "return", "rslt", ";", "}", ",", "[", "]", ")", ";", "}" ]
Configure to use locale names by default
[ "Configure", "to", "use", "locale", "names", "by", "default" ]
ac7a76c678a4eb8242a695d0ce133757345e6c31
https://github.com/angular-ui/ui-calendar/blob/ac7a76c678a4eb8242a695d0ce133757345e6c31/src/calendar.js#L208-L217
9,404
digiaonline/react-foundation
src/components/button.js
createButtonClassName
function createButtonClassName(props) { return createClassName( props.noDefaultClassName ? null : 'button', props.className, props.size, props.color, { 'hollow': props.isHollow, 'clear': props.isClear, 'expanded': props.isExpanded, 'disabled': props.isDisabled, 'dropdown': props.isDropdown, 'arrow-only': props.isArrowOnly }, generalClassNames(props) ); }
javascript
function createButtonClassName(props) { return createClassName( props.noDefaultClassName ? null : 'button', props.className, props.size, props.color, { 'hollow': props.isHollow, 'clear': props.isClear, 'expanded': props.isExpanded, 'disabled': props.isDisabled, 'dropdown': props.isDropdown, 'arrow-only': props.isArrowOnly }, generalClassNames(props) ); }
[ "function", "createButtonClassName", "(", "props", ")", "{", "return", "createClassName", "(", "props", ".", "noDefaultClassName", "?", "null", ":", "'button'", ",", "props", ".", "className", ",", "props", ".", "size", ",", "props", ".", "color", ",", "{", "'hollow'", ":", "props", ".", "isHollow", ",", "'clear'", ":", "props", ".", "isClear", ",", "'expanded'", ":", "props", ".", "isExpanded", ",", "'disabled'", ":", "props", ".", "isDisabled", ",", "'dropdown'", ":", "props", ".", "isDropdown", ",", "'arrow-only'", ":", "props", ".", "isArrowOnly", "}", ",", "generalClassNames", "(", "props", ")", ")", ";", "}" ]
Creates button class name from the given properties. @param {Object} props @returns {string}
[ "Creates", "button", "class", "name", "from", "the", "given", "properties", "." ]
20cd3e2ff04efe8a01cf68b671f3bf2eb68d9ed3
https://github.com/digiaonline/react-foundation/blob/20cd3e2ff04efe8a01cf68b671f3bf2eb68d9ed3/src/components/button.js#L59-L75
9,405
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
FeedMessage
function FeedMessage(properties) { this.entity = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function FeedMessage(properties) { this.entity = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "FeedMessage", "(", "properties", ")", "{", "this", ".", "entity", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a FeedMessage. @memberof transit_realtime @interface IFeedMessage @property {transit_realtime.IFeedHeader} header FeedMessage header @property {Array.<transit_realtime.IFeedEntity>|null} [entity] FeedMessage entity Constructs a new FeedMessage. @memberof transit_realtime @classdesc Represents a FeedMessage. @implements IFeedMessage @constructor @param {transit_realtime.IFeedMessage=} [properties] Properties to set
[ "Properties", "of", "a", "FeedMessage", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L53-L59
9,406
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
FeedHeader
function FeedHeader(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function FeedHeader(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "FeedHeader", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a FeedHeader. @memberof transit_realtime @interface IFeedHeader @property {string} gtfsRealtimeVersion FeedHeader gtfsRealtimeVersion @property {transit_realtime.FeedHeader.Incrementality|null} [incrementality] FeedHeader incrementality @property {number|Long|null} [timestamp] FeedHeader timestamp Constructs a new FeedHeader. @memberof transit_realtime @classdesc Represents a FeedHeader. @implements IFeedHeader @constructor @param {transit_realtime.IFeedHeader=} [properties] Properties to set
[ "Properties", "of", "a", "FeedHeader", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L291-L296
9,407
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
FeedEntity
function FeedEntity(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function FeedEntity(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "FeedEntity", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a FeedEntity. @memberof transit_realtime @interface IFeedEntity @property {string} id FeedEntity id @property {boolean|null} [isDeleted] FeedEntity isDeleted @property {transit_realtime.ITripUpdate|null} [tripUpdate] FeedEntity tripUpdate @property {transit_realtime.IVehiclePosition|null} [vehicle] FeedEntity vehicle @property {transit_realtime.IAlert|null} [alert] FeedEntity alert Constructs a new FeedEntity. @memberof transit_realtime @classdesc Represents a FeedEntity. @implements IFeedEntity @constructor @param {transit_realtime.IFeedEntity=} [properties] Properties to set
[ "Properties", "of", "a", "FeedEntity", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L566-L571
9,408
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
TripUpdate
function TripUpdate(properties) { this.stopTimeUpdate = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function TripUpdate(properties) { this.stopTimeUpdate = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "TripUpdate", "(", "properties", ")", "{", "this", ".", "stopTimeUpdate", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a TripUpdate. @memberof transit_realtime @interface ITripUpdate @property {transit_realtime.ITripDescriptor} trip TripUpdate trip @property {transit_realtime.IVehicleDescriptor|null} [vehicle] TripUpdate vehicle @property {Array.<transit_realtime.TripUpdate.IStopTimeUpdate>|null} [stopTimeUpdate] TripUpdate stopTimeUpdate @property {number|Long|null} [timestamp] TripUpdate timestamp @property {number|null} [delay] TripUpdate delay Constructs a new TripUpdate. @memberof transit_realtime @classdesc Represents a TripUpdate. @implements ITripUpdate @constructor @param {transit_realtime.ITripUpdate=} [properties] Properties to set
[ "Properties", "of", "a", "TripUpdate", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L857-L863
9,409
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
StopTimeEvent
function StopTimeEvent(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function StopTimeEvent(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "StopTimeEvent", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a StopTimeEvent. @memberof transit_realtime.TripUpdate @interface IStopTimeEvent @property {number|null} [delay] StopTimeEvent delay @property {number|Long|null} [time] StopTimeEvent time @property {number|null} [uncertainty] StopTimeEvent uncertainty Constructs a new StopTimeEvent. @memberof transit_realtime.TripUpdate @classdesc Represents a StopTimeEvent. @implements IStopTimeEvent @constructor @param {transit_realtime.TripUpdate.IStopTimeEvent=} [properties] Properties to set
[ "Properties", "of", "a", "StopTimeEvent", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L1175-L1180
9,410
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
StopTimeUpdate
function StopTimeUpdate(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function StopTimeUpdate(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "StopTimeUpdate", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a StopTimeUpdate. @memberof transit_realtime.TripUpdate @interface IStopTimeUpdate @property {number|null} [stopSequence] StopTimeUpdate stopSequence @property {string|null} [stopId] StopTimeUpdate stopId @property {transit_realtime.TripUpdate.IStopTimeEvent|null} [arrival] StopTimeUpdate arrival @property {transit_realtime.TripUpdate.IStopTimeEvent|null} [departure] StopTimeUpdate departure @property {transit_realtime.TripUpdate.StopTimeUpdate.ScheduleRelationship|null} [scheduleRelationship] StopTimeUpdate scheduleRelationship Constructs a new StopTimeUpdate. @memberof transit_realtime.TripUpdate @classdesc Represents a StopTimeUpdate. @implements IStopTimeUpdate @constructor @param {transit_realtime.TripUpdate.IStopTimeUpdate=} [properties] Properties to set
[ "Properties", "of", "a", "StopTimeUpdate", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L1423-L1428
9,411
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
VehiclePosition
function VehiclePosition(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function VehiclePosition(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "VehiclePosition", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a VehiclePosition. @memberof transit_realtime @interface IVehiclePosition @property {transit_realtime.ITripDescriptor|null} [trip] VehiclePosition trip @property {transit_realtime.IVehicleDescriptor|null} [vehicle] VehiclePosition vehicle @property {transit_realtime.IPosition|null} [position] VehiclePosition position @property {number|null} [currentStopSequence] VehiclePosition currentStopSequence @property {string|null} [stopId] VehiclePosition stopId @property {transit_realtime.VehiclePosition.VehicleStopStatus|null} [currentStatus] VehiclePosition currentStatus @property {number|Long|null} [timestamp] VehiclePosition timestamp @property {transit_realtime.VehiclePosition.CongestionLevel|null} [congestionLevel] VehiclePosition congestionLevel @property {transit_realtime.VehiclePosition.OccupancyStatus|null} [occupancyStatus] VehiclePosition occupancyStatus Constructs a new VehiclePosition. @memberof transit_realtime @classdesc Represents a VehiclePosition. @implements IVehiclePosition @constructor @param {transit_realtime.IVehiclePosition=} [properties] Properties to set
[ "Properties", "of", "a", "VehiclePosition", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L1750-L1755
9,412
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
Alert
function Alert(properties) { this.activePeriod = []; this.informedEntity = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Alert(properties) { this.activePeriod = []; this.informedEntity = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Alert", "(", "properties", ")", "{", "this", ".", "activePeriod", "=", "[", "]", ";", "this", ".", "informedEntity", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of an Alert. @memberof transit_realtime @interface IAlert @property {Array.<transit_realtime.ITimeRange>|null} [activePeriod] Alert activePeriod @property {Array.<transit_realtime.IEntitySelector>|null} [informedEntity] Alert informedEntity @property {transit_realtime.Alert.Cause|null} [cause] Alert cause @property {transit_realtime.Alert.Effect|null} [effect] Alert effect @property {transit_realtime.ITranslatedString|null} [url] Alert url @property {transit_realtime.ITranslatedString|null} [headerText] Alert headerText @property {transit_realtime.ITranslatedString|null} [descriptionText] Alert descriptionText @property {transit_realtime.ITranslatedString|null} [ttsHeaderText] Alert ttsHeaderText @property {transit_realtime.ITranslatedString|null} [ttsDescriptionText] Alert ttsDescriptionText @property {transit_realtime.Alert.SeverityLevel|null} [severityLevel] Alert severityLevel Constructs a new Alert. @memberof transit_realtime @classdesc Represents an Alert. @implements IAlert @constructor @param {transit_realtime.IAlert=} [properties] Properties to set
[ "Properties", "of", "an", "Alert", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L2288-L2295
9,413
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
TimeRange
function TimeRange(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function TimeRange(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "TimeRange", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a TimeRange. @memberof transit_realtime @interface ITimeRange @property {number|Long|null} [start] TimeRange start @property {number|Long|null} [end] TimeRange end Constructs a new TimeRange. @memberof transit_realtime @classdesc Represents a TimeRange. @implements ITimeRange @constructor @param {transit_realtime.ITimeRange=} [properties] Properties to set
[ "Properties", "of", "a", "TimeRange", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L2956-L2961
9,414
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
Position
function Position(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Position(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Position", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Position. @memberof transit_realtime @interface IPosition @property {number} latitude Position latitude @property {number} longitude Position longitude @property {number|null} [bearing] Position bearing @property {number|null} [odometer] Position odometer @property {number|null} [speed] Position speed Constructs a new Position. @memberof transit_realtime @classdesc Represents a Position. @implements IPosition @constructor @param {transit_realtime.IPosition=} [properties] Properties to set
[ "Properties", "of", "a", "Position", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L3197-L3202
9,415
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
TripDescriptor
function TripDescriptor(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function TripDescriptor(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "TripDescriptor", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a TripDescriptor. @memberof transit_realtime @interface ITripDescriptor @property {string|null} [tripId] TripDescriptor tripId @property {string|null} [routeId] TripDescriptor routeId @property {number|null} [directionId] TripDescriptor directionId @property {string|null} [startTime] TripDescriptor startTime @property {string|null} [startDate] TripDescriptor startDate @property {transit_realtime.TripDescriptor.ScheduleRelationship|null} [scheduleRelationship] TripDescriptor scheduleRelationship Constructs a new TripDescriptor. @memberof transit_realtime @classdesc Represents a TripDescriptor. @implements ITripDescriptor @constructor @param {transit_realtime.ITripDescriptor=} [properties] Properties to set
[ "Properties", "of", "a", "TripDescriptor", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L3474-L3479
9,416
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
VehicleDescriptor
function VehicleDescriptor(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function VehicleDescriptor(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "VehicleDescriptor", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a VehicleDescriptor. @memberof transit_realtime @interface IVehicleDescriptor @property {string|null} [id] VehicleDescriptor id @property {string|null} [label] VehicleDescriptor label @property {string|null} [licensePlate] VehicleDescriptor licensePlate Constructs a new VehicleDescriptor. @memberof transit_realtime @classdesc Represents a VehicleDescriptor. @implements IVehicleDescriptor @constructor @param {transit_realtime.IVehicleDescriptor=} [properties] Properties to set
[ "Properties", "of", "a", "VehicleDescriptor", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L3817-L3822
9,417
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
EntitySelector
function EntitySelector(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function EntitySelector(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "EntitySelector", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of an EntitySelector. @memberof transit_realtime @interface IEntitySelector @property {string|null} [agencyId] EntitySelector agencyId @property {string|null} [routeId] EntitySelector routeId @property {number|null} [routeType] EntitySelector routeType @property {transit_realtime.ITripDescriptor|null} [trip] EntitySelector trip @property {string|null} [stopId] EntitySelector stopId Constructs a new EntitySelector. @memberof transit_realtime @classdesc Represents an EntitySelector. @implements IEntitySelector @constructor @param {transit_realtime.IEntitySelector=} [properties] Properties to set
[ "Properties", "of", "an", "EntitySelector", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L4051-L4056
9,418
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
TranslatedString
function TranslatedString(properties) { this.translation = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function TranslatedString(properties) { this.translation = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "TranslatedString", "(", "properties", ")", "{", "this", ".", "translation", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a TranslatedString. @memberof transit_realtime @interface ITranslatedString @property {Array.<transit_realtime.TranslatedString.ITranslation>|null} [translation] TranslatedString translation Constructs a new TranslatedString. @memberof transit_realtime @classdesc Represents a TranslatedString. @implements ITranslatedString @constructor @param {transit_realtime.ITranslatedString=} [properties] Properties to set
[ "Properties", "of", "a", "TranslatedString", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L4328-L4334
9,419
MobilityData/gtfs-realtime-bindings
nodejs/gtfs-realtime.js
Translation
function Translation(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Translation(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Translation", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Translation. @memberof transit_realtime.TranslatedString @interface ITranslation @property {string} text Translation text @property {string|null} [language] Translation language Constructs a new Translation. @memberof transit_realtime.TranslatedString @classdesc Represents a Translation. @implements ITranslation @constructor @param {transit_realtime.TranslatedString.ITranslation=} [properties] Properties to set
[ "Properties", "of", "a", "Translation", "." ]
2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487
https://github.com/MobilityData/gtfs-realtime-bindings/blob/2ede9aeee2d9e8ec62ecc7684b8ee624fcfc5487/nodejs/gtfs-realtime.js#L4534-L4539
9,420
Microsoft/vscode-css-languageservice
build/mdn/mdn-data-importer.js
extractMDNProperties
function extractMDNProperties(mdnEntry) { if (mdnEntry.status === 'standard') { return { syntax: mdnEntry.syntax } } return { status: abbreviateStatus(mdnEntry.status), syntax: mdnEntry.syntax } }
javascript
function extractMDNProperties(mdnEntry) { if (mdnEntry.status === 'standard') { return { syntax: mdnEntry.syntax } } return { status: abbreviateStatus(mdnEntry.status), syntax: mdnEntry.syntax } }
[ "function", "extractMDNProperties", "(", "mdnEntry", ")", "{", "if", "(", "mdnEntry", ".", "status", "===", "'standard'", ")", "{", "return", "{", "syntax", ":", "mdnEntry", ".", "syntax", "}", "}", "return", "{", "status", ":", "abbreviateStatus", "(", "mdnEntry", ".", "status", ")", ",", "syntax", ":", "mdnEntry", ".", "syntax", "}", "}" ]
Extract only the MDN data that we use
[ "Extract", "only", "the", "MDN", "data", "that", "we", "use" ]
2d0a8b93fa1cf138ccb936ab144303aea3e36d05
https://github.com/Microsoft/vscode-css-languageservice/blob/2d0a8b93fa1cf138ccb936ab144303aea3e36d05/build/mdn/mdn-data-importer.js#L76-L87
9,421
Microsoft/vscode-css-languageservice
build/generate_browserjs.js
convertEntry
function convertEntry(entry) { entry.description = entry.desc delete entry.desc if (entry.values) { entry.values.forEach(v => { v.description = v.desc delete v.desc if (v.browsers) { if (v.browsers === 'all') { delete v.browsers } else { v.browsers = entry.browsers.split(',') if (v.browsers.length === 1 && v.browsers[0] === "all") { delete v.browsers } } } }) } if (entry.browsers) { if (entry.browsers === 'all') { delete entry.browsers } else { entry.browsers = entry.browsers.split(',') } } if (entry.restriction) { entry.restrictions = entry.restriction.split(',').map((s) => { return s.trim(); }); if (entry.restrictions.length === 1 && entry.restrictions[0] === "none") { delete entry.restrictions } } else { delete entry.restrictions } delete entry.restriction if (entry.status) { entry.status = expandEntryStatus(entry.status) } }
javascript
function convertEntry(entry) { entry.description = entry.desc delete entry.desc if (entry.values) { entry.values.forEach(v => { v.description = v.desc delete v.desc if (v.browsers) { if (v.browsers === 'all') { delete v.browsers } else { v.browsers = entry.browsers.split(',') if (v.browsers.length === 1 && v.browsers[0] === "all") { delete v.browsers } } } }) } if (entry.browsers) { if (entry.browsers === 'all') { delete entry.browsers } else { entry.browsers = entry.browsers.split(',') } } if (entry.restriction) { entry.restrictions = entry.restriction.split(',').map((s) => { return s.trim(); }); if (entry.restrictions.length === 1 && entry.restrictions[0] === "none") { delete entry.restrictions } } else { delete entry.restrictions } delete entry.restriction if (entry.status) { entry.status = expandEntryStatus(entry.status) } }
[ "function", "convertEntry", "(", "entry", ")", "{", "entry", ".", "description", "=", "entry", ".", "desc", "delete", "entry", ".", "desc", "if", "(", "entry", ".", "values", ")", "{", "entry", ".", "values", ".", "forEach", "(", "v", "=>", "{", "v", ".", "description", "=", "v", ".", "desc", "delete", "v", ".", "desc", "if", "(", "v", ".", "browsers", ")", "{", "if", "(", "v", ".", "browsers", "===", "'all'", ")", "{", "delete", "v", ".", "browsers", "}", "else", "{", "v", ".", "browsers", "=", "entry", ".", "browsers", ".", "split", "(", "','", ")", "if", "(", "v", ".", "browsers", ".", "length", "===", "1", "&&", "v", ".", "browsers", "[", "0", "]", "===", "\"all\"", ")", "{", "delete", "v", ".", "browsers", "}", "}", "}", "}", ")", "}", "if", "(", "entry", ".", "browsers", ")", "{", "if", "(", "entry", ".", "browsers", "===", "'all'", ")", "{", "delete", "entry", ".", "browsers", "}", "else", "{", "entry", ".", "browsers", "=", "entry", ".", "browsers", ".", "split", "(", "','", ")", "}", "}", "if", "(", "entry", ".", "restriction", ")", "{", "entry", ".", "restrictions", "=", "entry", ".", "restriction", ".", "split", "(", "','", ")", ".", "map", "(", "(", "s", ")", "=>", "{", "return", "s", ".", "trim", "(", ")", ";", "}", ")", ";", "if", "(", "entry", ".", "restrictions", ".", "length", "===", "1", "&&", "entry", ".", "restrictions", "[", "0", "]", "===", "\"none\"", ")", "{", "delete", "entry", ".", "restrictions", "}", "}", "else", "{", "delete", "entry", ".", "restrictions", "}", "delete", "entry", ".", "restriction", "if", "(", "entry", ".", "status", ")", "{", "entry", ".", "status", "=", "expandEntryStatus", "(", "entry", ".", "status", ")", "}", "}" ]
Temporarily convert old entry to new entry Todo@Pine: Change MDN data generation so this yields new entry
[ "Temporarily", "convert", "old", "entry", "to", "new", "entry", "Todo" ]
2d0a8b93fa1cf138ccb936ab144303aea3e36d05
https://github.com/Microsoft/vscode-css-languageservice/blob/2d0a8b93fa1cf138ccb936ab144303aea3e36d05/build/generate_browserjs.js#L422-L465
9,422
dailymotion/vast-client-js
dist/vast-client-node.js
childByName
function childByName(node, name) { var childNodes = node.childNodes; for (var childKey in childNodes) { var child = childNodes[childKey]; if (child.nodeName === name) { return child; } } }
javascript
function childByName(node, name) { var childNodes = node.childNodes; for (var childKey in childNodes) { var child = childNodes[childKey]; if (child.nodeName === name) { return child; } } }
[ "function", "childByName", "(", "node", ",", "name", ")", "{", "var", "childNodes", "=", "node", ".", "childNodes", ";", "for", "(", "var", "childKey", "in", "childNodes", ")", "{", "var", "child", "=", "childNodes", "[", "childKey", "]", ";", "if", "(", "child", ".", "nodeName", "===", "name", ")", "{", "return", "child", ";", "}", "}", "}" ]
This module provides support methods to the parsing classes. Returns the first element of the given node which nodeName matches the given name. @param {Object} node - The node to use to find a match. @param {String} name - The name to look for. @return {Object}
[ "This", "module", "provides", "support", "methods", "to", "the", "parsing", "classes", ".", "Returns", "the", "first", "element", "of", "the", "given", "node", "which", "nodeName", "matches", "the", "given", "name", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/dist/vast-client-node.js#L252-L262
9,423
dailymotion/vast-client-js
dist/vast-client-node.js
resolveVastAdTagURI
function resolveVastAdTagURI(vastAdTagUrl, originalUrl) { if (!originalUrl) { return vastAdTagUrl; } if (vastAdTagUrl.indexOf('//') === 0) { var _location = location, protocol = _location.protocol; return '' + protocol + vastAdTagUrl; } if (vastAdTagUrl.indexOf('://') === -1) { // Resolve relative URLs (mainly for unit testing) var baseURL = originalUrl.slice(0, originalUrl.lastIndexOf('/')); return baseURL + '/' + vastAdTagUrl; } return vastAdTagUrl; }
javascript
function resolveVastAdTagURI(vastAdTagUrl, originalUrl) { if (!originalUrl) { return vastAdTagUrl; } if (vastAdTagUrl.indexOf('//') === 0) { var _location = location, protocol = _location.protocol; return '' + protocol + vastAdTagUrl; } if (vastAdTagUrl.indexOf('://') === -1) { // Resolve relative URLs (mainly for unit testing) var baseURL = originalUrl.slice(0, originalUrl.lastIndexOf('/')); return baseURL + '/' + vastAdTagUrl; } return vastAdTagUrl; }
[ "function", "resolveVastAdTagURI", "(", "vastAdTagUrl", ",", "originalUrl", ")", "{", "if", "(", "!", "originalUrl", ")", "{", "return", "vastAdTagUrl", ";", "}", "if", "(", "vastAdTagUrl", ".", "indexOf", "(", "'//'", ")", "===", "0", ")", "{", "var", "_location", "=", "location", ",", "protocol", "=", "_location", ".", "protocol", ";", "return", "''", "+", "protocol", "+", "vastAdTagUrl", ";", "}", "if", "(", "vastAdTagUrl", ".", "indexOf", "(", "'://'", ")", "===", "-", "1", ")", "{", "// Resolve relative URLs (mainly for unit testing)", "var", "baseURL", "=", "originalUrl", ".", "slice", "(", "0", ",", "originalUrl", ".", "lastIndexOf", "(", "'/'", ")", ")", ";", "return", "baseURL", "+", "'/'", "+", "vastAdTagUrl", ";", "}", "return", "vastAdTagUrl", ";", "}" ]
Converts relative vastAdTagUri. @param {String} vastAdTagUrl - The url to resolve. @param {String} originalUrl - The original url. @return {String}
[ "Converts", "relative", "vastAdTagUri", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/dist/vast-client-node.js#L290-L309
9,424
dailymotion/vast-client-js
dist/vast-client-node.js
mergeWrapperAdData
function mergeWrapperAdData(unwrappedAd, wrapper) { unwrappedAd.errorURLTemplates = wrapper.errorURLTemplates.concat(unwrappedAd.errorURLTemplates); unwrappedAd.impressionURLTemplates = wrapper.impressionURLTemplates.concat(unwrappedAd.impressionURLTemplates); unwrappedAd.extensions = wrapper.extensions.concat(unwrappedAd.extensions); unwrappedAd.creatives.forEach(function (creative) { if (wrapper.trackingEvents && wrapper.trackingEvents[creative.type]) { for (var eventName in wrapper.trackingEvents[creative.type]) { var urls = wrapper.trackingEvents[creative.type][eventName]; if (!Array.isArray(creative.trackingEvents[eventName])) { creative.trackingEvents[eventName] = []; } creative.trackingEvents[eventName] = creative.trackingEvents[eventName].concat(urls); } } }); if (wrapper.videoClickTrackingURLTemplates && wrapper.videoClickTrackingURLTemplates.length) { unwrappedAd.creatives.forEach(function (creative) { if (creative.type === 'linear') { creative.videoClickTrackingURLTemplates = creative.videoClickTrackingURLTemplates.concat(wrapper.videoClickTrackingURLTemplates); } }); } if (wrapper.videoCustomClickURLTemplates && wrapper.videoCustomClickURLTemplates.length) { unwrappedAd.creatives.forEach(function (creative) { if (creative.type === 'linear') { creative.videoCustomClickURLTemplates = creative.videoCustomClickURLTemplates.concat(wrapper.videoCustomClickURLTemplates); } }); } // VAST 2.0 support - Use Wrapper/linear/clickThrough when Inline/Linear/clickThrough is null if (wrapper.videoClickThroughURLTemplate) { unwrappedAd.creatives.forEach(function (creative) { if (creative.type === 'linear' && (creative.videoClickThroughURLTemplate === null || typeof creative.videoClickThroughURLTemplate === 'undefined')) { creative.videoClickThroughURLTemplate = wrapper.videoClickThroughURLTemplate; } }); } }
javascript
function mergeWrapperAdData(unwrappedAd, wrapper) { unwrappedAd.errorURLTemplates = wrapper.errorURLTemplates.concat(unwrappedAd.errorURLTemplates); unwrappedAd.impressionURLTemplates = wrapper.impressionURLTemplates.concat(unwrappedAd.impressionURLTemplates); unwrappedAd.extensions = wrapper.extensions.concat(unwrappedAd.extensions); unwrappedAd.creatives.forEach(function (creative) { if (wrapper.trackingEvents && wrapper.trackingEvents[creative.type]) { for (var eventName in wrapper.trackingEvents[creative.type]) { var urls = wrapper.trackingEvents[creative.type][eventName]; if (!Array.isArray(creative.trackingEvents[eventName])) { creative.trackingEvents[eventName] = []; } creative.trackingEvents[eventName] = creative.trackingEvents[eventName].concat(urls); } } }); if (wrapper.videoClickTrackingURLTemplates && wrapper.videoClickTrackingURLTemplates.length) { unwrappedAd.creatives.forEach(function (creative) { if (creative.type === 'linear') { creative.videoClickTrackingURLTemplates = creative.videoClickTrackingURLTemplates.concat(wrapper.videoClickTrackingURLTemplates); } }); } if (wrapper.videoCustomClickURLTemplates && wrapper.videoCustomClickURLTemplates.length) { unwrappedAd.creatives.forEach(function (creative) { if (creative.type === 'linear') { creative.videoCustomClickURLTemplates = creative.videoCustomClickURLTemplates.concat(wrapper.videoCustomClickURLTemplates); } }); } // VAST 2.0 support - Use Wrapper/linear/clickThrough when Inline/Linear/clickThrough is null if (wrapper.videoClickThroughURLTemplate) { unwrappedAd.creatives.forEach(function (creative) { if (creative.type === 'linear' && (creative.videoClickThroughURLTemplate === null || typeof creative.videoClickThroughURLTemplate === 'undefined')) { creative.videoClickThroughURLTemplate = wrapper.videoClickThroughURLTemplate; } }); } }
[ "function", "mergeWrapperAdData", "(", "unwrappedAd", ",", "wrapper", ")", "{", "unwrappedAd", ".", "errorURLTemplates", "=", "wrapper", ".", "errorURLTemplates", ".", "concat", "(", "unwrappedAd", ".", "errorURLTemplates", ")", ";", "unwrappedAd", ".", "impressionURLTemplates", "=", "wrapper", ".", "impressionURLTemplates", ".", "concat", "(", "unwrappedAd", ".", "impressionURLTemplates", ")", ";", "unwrappedAd", ".", "extensions", "=", "wrapper", ".", "extensions", ".", "concat", "(", "unwrappedAd", ".", "extensions", ")", ";", "unwrappedAd", ".", "creatives", ".", "forEach", "(", "function", "(", "creative", ")", "{", "if", "(", "wrapper", ".", "trackingEvents", "&&", "wrapper", ".", "trackingEvents", "[", "creative", ".", "type", "]", ")", "{", "for", "(", "var", "eventName", "in", "wrapper", ".", "trackingEvents", "[", "creative", ".", "type", "]", ")", "{", "var", "urls", "=", "wrapper", ".", "trackingEvents", "[", "creative", ".", "type", "]", "[", "eventName", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "creative", ".", "trackingEvents", "[", "eventName", "]", ")", ")", "{", "creative", ".", "trackingEvents", "[", "eventName", "]", "=", "[", "]", ";", "}", "creative", ".", "trackingEvents", "[", "eventName", "]", "=", "creative", ".", "trackingEvents", "[", "eventName", "]", ".", "concat", "(", "urls", ")", ";", "}", "}", "}", ")", ";", "if", "(", "wrapper", ".", "videoClickTrackingURLTemplates", "&&", "wrapper", ".", "videoClickTrackingURLTemplates", ".", "length", ")", "{", "unwrappedAd", ".", "creatives", ".", "forEach", "(", "function", "(", "creative", ")", "{", "if", "(", "creative", ".", "type", "===", "'linear'", ")", "{", "creative", ".", "videoClickTrackingURLTemplates", "=", "creative", ".", "videoClickTrackingURLTemplates", ".", "concat", "(", "wrapper", ".", "videoClickTrackingURLTemplates", ")", ";", "}", "}", ")", ";", "}", "if", "(", "wrapper", ".", "videoCustomClickURLTemplates", "&&", "wrapper", ".", "videoCustomClickURLTemplates", ".", "length", ")", "{", "unwrappedAd", ".", "creatives", ".", "forEach", "(", "function", "(", "creative", ")", "{", "if", "(", "creative", ".", "type", "===", "'linear'", ")", "{", "creative", ".", "videoCustomClickURLTemplates", "=", "creative", ".", "videoCustomClickURLTemplates", ".", "concat", "(", "wrapper", ".", "videoCustomClickURLTemplates", ")", ";", "}", "}", ")", ";", "}", "// VAST 2.0 support - Use Wrapper/linear/clickThrough when Inline/Linear/clickThrough is null", "if", "(", "wrapper", ".", "videoClickThroughURLTemplate", ")", "{", "unwrappedAd", ".", "creatives", ".", "forEach", "(", "function", "(", "creative", ")", "{", "if", "(", "creative", ".", "type", "===", "'linear'", "&&", "(", "creative", ".", "videoClickThroughURLTemplate", "===", "null", "||", "typeof", "creative", ".", "videoClickThroughURLTemplate", "===", "'undefined'", ")", ")", "{", "creative", ".", "videoClickThroughURLTemplate", "=", "wrapper", ".", "videoClickThroughURLTemplate", ";", "}", "}", ")", ";", "}", "}" ]
Merges the data between an unwrapped ad and his wrapper. @param {Ad} unwrappedAd - The 'unwrapped' Ad. @param {Ad} wrapper - The wrapper Ad. @return {void}
[ "Merges", "the", "data", "between", "an", "unwrapped", "ad", "and", "his", "wrapper", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/dist/vast-client-node.js#L416-L457
9,425
dailymotion/vast-client-js
dist/vast-client-node.js
parseCreativeNonLinear
function parseCreativeNonLinear(creativeElement, creativeAttributes) { var creative = new CreativeNonLinear(creativeAttributes); parserUtils.childrenByName(creativeElement, 'TrackingEvents').forEach(function (trackingEventsElement) { var eventName = void 0, trackingURLTemplate = void 0; parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { eventName = trackingElement.getAttribute('event'); trackingURLTemplate = parserUtils.parseNodeText(trackingElement); if (eventName && trackingURLTemplate) { if (!Array.isArray(creative.trackingEvents[eventName])) { creative.trackingEvents[eventName] = []; } creative.trackingEvents[eventName].push(trackingURLTemplate); } }); }); parserUtils.childrenByName(creativeElement, 'NonLinear').forEach(function (nonlinearResource) { var nonlinearAd = new NonLinearAd(); nonlinearAd.id = nonlinearResource.getAttribute('id') || null; nonlinearAd.width = nonlinearResource.getAttribute('width'); nonlinearAd.height = nonlinearResource.getAttribute('height'); nonlinearAd.expandedWidth = nonlinearResource.getAttribute('expandedWidth'); nonlinearAd.expandedHeight = nonlinearResource.getAttribute('expandedHeight'); nonlinearAd.scalable = parserUtils.parseBoolean(nonlinearResource.getAttribute('scalable')); nonlinearAd.maintainAspectRatio = parserUtils.parseBoolean(nonlinearResource.getAttribute('maintainAspectRatio')); nonlinearAd.minSuggestedDuration = parserUtils.parseDuration(nonlinearResource.getAttribute('minSuggestedDuration')); nonlinearAd.apiFramework = nonlinearResource.getAttribute('apiFramework'); parserUtils.childrenByName(nonlinearResource, 'HTMLResource').forEach(function (htmlElement) { nonlinearAd.type = htmlElement.getAttribute('creativeType') || 'text/html'; nonlinearAd.htmlResource = parserUtils.parseNodeText(htmlElement); }); parserUtils.childrenByName(nonlinearResource, 'IFrameResource').forEach(function (iframeElement) { nonlinearAd.type = iframeElement.getAttribute('creativeType') || 0; nonlinearAd.iframeResource = parserUtils.parseNodeText(iframeElement); }); parserUtils.childrenByName(nonlinearResource, 'StaticResource').forEach(function (staticElement) { nonlinearAd.type = staticElement.getAttribute('creativeType') || 0; nonlinearAd.staticResource = parserUtils.parseNodeText(staticElement); }); var adParamsElement = parserUtils.childByName(nonlinearResource, 'AdParameters'); if (adParamsElement) { nonlinearAd.adParameters = parserUtils.parseNodeText(adParamsElement); } nonlinearAd.nonlinearClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(nonlinearResource, 'NonLinearClickThrough')); parserUtils.childrenByName(nonlinearResource, 'NonLinearClickTracking').forEach(function (clickTrackingElement) { nonlinearAd.nonlinearClickTrackingURLTemplates.push(parserUtils.parseNodeText(clickTrackingElement)); }); creative.variations.push(nonlinearAd); }); return creative; }
javascript
function parseCreativeNonLinear(creativeElement, creativeAttributes) { var creative = new CreativeNonLinear(creativeAttributes); parserUtils.childrenByName(creativeElement, 'TrackingEvents').forEach(function (trackingEventsElement) { var eventName = void 0, trackingURLTemplate = void 0; parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { eventName = trackingElement.getAttribute('event'); trackingURLTemplate = parserUtils.parseNodeText(trackingElement); if (eventName && trackingURLTemplate) { if (!Array.isArray(creative.trackingEvents[eventName])) { creative.trackingEvents[eventName] = []; } creative.trackingEvents[eventName].push(trackingURLTemplate); } }); }); parserUtils.childrenByName(creativeElement, 'NonLinear').forEach(function (nonlinearResource) { var nonlinearAd = new NonLinearAd(); nonlinearAd.id = nonlinearResource.getAttribute('id') || null; nonlinearAd.width = nonlinearResource.getAttribute('width'); nonlinearAd.height = nonlinearResource.getAttribute('height'); nonlinearAd.expandedWidth = nonlinearResource.getAttribute('expandedWidth'); nonlinearAd.expandedHeight = nonlinearResource.getAttribute('expandedHeight'); nonlinearAd.scalable = parserUtils.parseBoolean(nonlinearResource.getAttribute('scalable')); nonlinearAd.maintainAspectRatio = parserUtils.parseBoolean(nonlinearResource.getAttribute('maintainAspectRatio')); nonlinearAd.minSuggestedDuration = parserUtils.parseDuration(nonlinearResource.getAttribute('minSuggestedDuration')); nonlinearAd.apiFramework = nonlinearResource.getAttribute('apiFramework'); parserUtils.childrenByName(nonlinearResource, 'HTMLResource').forEach(function (htmlElement) { nonlinearAd.type = htmlElement.getAttribute('creativeType') || 'text/html'; nonlinearAd.htmlResource = parserUtils.parseNodeText(htmlElement); }); parserUtils.childrenByName(nonlinearResource, 'IFrameResource').forEach(function (iframeElement) { nonlinearAd.type = iframeElement.getAttribute('creativeType') || 0; nonlinearAd.iframeResource = parserUtils.parseNodeText(iframeElement); }); parserUtils.childrenByName(nonlinearResource, 'StaticResource').forEach(function (staticElement) { nonlinearAd.type = staticElement.getAttribute('creativeType') || 0; nonlinearAd.staticResource = parserUtils.parseNodeText(staticElement); }); var adParamsElement = parserUtils.childByName(nonlinearResource, 'AdParameters'); if (adParamsElement) { nonlinearAd.adParameters = parserUtils.parseNodeText(adParamsElement); } nonlinearAd.nonlinearClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(nonlinearResource, 'NonLinearClickThrough')); parserUtils.childrenByName(nonlinearResource, 'NonLinearClickTracking').forEach(function (clickTrackingElement) { nonlinearAd.nonlinearClickTrackingURLTemplates.push(parserUtils.parseNodeText(clickTrackingElement)); }); creative.variations.push(nonlinearAd); }); return creative; }
[ "function", "parseCreativeNonLinear", "(", "creativeElement", ",", "creativeAttributes", ")", "{", "var", "creative", "=", "new", "CreativeNonLinear", "(", "creativeAttributes", ")", ";", "parserUtils", ".", "childrenByName", "(", "creativeElement", ",", "'TrackingEvents'", ")", ".", "forEach", "(", "function", "(", "trackingEventsElement", ")", "{", "var", "eventName", "=", "void", "0", ",", "trackingURLTemplate", "=", "void", "0", ";", "parserUtils", ".", "childrenByName", "(", "trackingEventsElement", ",", "'Tracking'", ")", ".", "forEach", "(", "function", "(", "trackingElement", ")", "{", "eventName", "=", "trackingElement", ".", "getAttribute", "(", "'event'", ")", ";", "trackingURLTemplate", "=", "parserUtils", ".", "parseNodeText", "(", "trackingElement", ")", ";", "if", "(", "eventName", "&&", "trackingURLTemplate", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "creative", ".", "trackingEvents", "[", "eventName", "]", ")", ")", "{", "creative", ".", "trackingEvents", "[", "eventName", "]", "=", "[", "]", ";", "}", "creative", ".", "trackingEvents", "[", "eventName", "]", ".", "push", "(", "trackingURLTemplate", ")", ";", "}", "}", ")", ";", "}", ")", ";", "parserUtils", ".", "childrenByName", "(", "creativeElement", ",", "'NonLinear'", ")", ".", "forEach", "(", "function", "(", "nonlinearResource", ")", "{", "var", "nonlinearAd", "=", "new", "NonLinearAd", "(", ")", ";", "nonlinearAd", ".", "id", "=", "nonlinearResource", ".", "getAttribute", "(", "'id'", ")", "||", "null", ";", "nonlinearAd", ".", "width", "=", "nonlinearResource", ".", "getAttribute", "(", "'width'", ")", ";", "nonlinearAd", ".", "height", "=", "nonlinearResource", ".", "getAttribute", "(", "'height'", ")", ";", "nonlinearAd", ".", "expandedWidth", "=", "nonlinearResource", ".", "getAttribute", "(", "'expandedWidth'", ")", ";", "nonlinearAd", ".", "expandedHeight", "=", "nonlinearResource", ".", "getAttribute", "(", "'expandedHeight'", ")", ";", "nonlinearAd", ".", "scalable", "=", "parserUtils", ".", "parseBoolean", "(", "nonlinearResource", ".", "getAttribute", "(", "'scalable'", ")", ")", ";", "nonlinearAd", ".", "maintainAspectRatio", "=", "parserUtils", ".", "parseBoolean", "(", "nonlinearResource", ".", "getAttribute", "(", "'maintainAspectRatio'", ")", ")", ";", "nonlinearAd", ".", "minSuggestedDuration", "=", "parserUtils", ".", "parseDuration", "(", "nonlinearResource", ".", "getAttribute", "(", "'minSuggestedDuration'", ")", ")", ";", "nonlinearAd", ".", "apiFramework", "=", "nonlinearResource", ".", "getAttribute", "(", "'apiFramework'", ")", ";", "parserUtils", ".", "childrenByName", "(", "nonlinearResource", ",", "'HTMLResource'", ")", ".", "forEach", "(", "function", "(", "htmlElement", ")", "{", "nonlinearAd", ".", "type", "=", "htmlElement", ".", "getAttribute", "(", "'creativeType'", ")", "||", "'text/html'", ";", "nonlinearAd", ".", "htmlResource", "=", "parserUtils", ".", "parseNodeText", "(", "htmlElement", ")", ";", "}", ")", ";", "parserUtils", ".", "childrenByName", "(", "nonlinearResource", ",", "'IFrameResource'", ")", ".", "forEach", "(", "function", "(", "iframeElement", ")", "{", "nonlinearAd", ".", "type", "=", "iframeElement", ".", "getAttribute", "(", "'creativeType'", ")", "||", "0", ";", "nonlinearAd", ".", "iframeResource", "=", "parserUtils", ".", "parseNodeText", "(", "iframeElement", ")", ";", "}", ")", ";", "parserUtils", ".", "childrenByName", "(", "nonlinearResource", ",", "'StaticResource'", ")", ".", "forEach", "(", "function", "(", "staticElement", ")", "{", "nonlinearAd", ".", "type", "=", "staticElement", ".", "getAttribute", "(", "'creativeType'", ")", "||", "0", ";", "nonlinearAd", ".", "staticResource", "=", "parserUtils", ".", "parseNodeText", "(", "staticElement", ")", ";", "}", ")", ";", "var", "adParamsElement", "=", "parserUtils", ".", "childByName", "(", "nonlinearResource", ",", "'AdParameters'", ")", ";", "if", "(", "adParamsElement", ")", "{", "nonlinearAd", ".", "adParameters", "=", "parserUtils", ".", "parseNodeText", "(", "adParamsElement", ")", ";", "}", "nonlinearAd", ".", "nonlinearClickThroughURLTemplate", "=", "parserUtils", ".", "parseNodeText", "(", "parserUtils", ".", "childByName", "(", "nonlinearResource", ",", "'NonLinearClickThrough'", ")", ")", ";", "parserUtils", ".", "childrenByName", "(", "nonlinearResource", ",", "'NonLinearClickTracking'", ")", ".", "forEach", "(", "function", "(", "clickTrackingElement", ")", "{", "nonlinearAd", ".", "nonlinearClickTrackingURLTemplates", ".", "push", "(", "parserUtils", ".", "parseNodeText", "(", "clickTrackingElement", ")", ")", ";", "}", ")", ";", "creative", ".", "variations", ".", "push", "(", "nonlinearAd", ")", ";", "}", ")", ";", "return", "creative", ";", "}" ]
This module provides methods to parse a VAST NonLinear Element. Parses a NonLinear element. @param {any} creativeElement - The VAST NonLinear element to parse. @param {any} creativeAttributes - The attributes of the NonLinear (optional). @return {CreativeNonLinear}
[ "This", "module", "provides", "methods", "to", "parse", "a", "VAST", "NonLinear", "Element", ".", "Parses", "a", "NonLinear", "element", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/dist/vast-client-node.js#L825-L885
9,426
dailymotion/vast-client-js
dist/vast-client-node.js
parseInLine
function parseInLine(inLineElement) { var childNodes = inLineElement.childNodes; var ad = new Ad(); ad.id = inLineElement.getAttribute('id') || null; ad.sequence = inLineElement.getAttribute('sequence') || null; for (var nodeKey in childNodes) { var node = childNodes[nodeKey]; switch (node.nodeName) { case 'Error': ad.errorURLTemplates.push(parserUtils.parseNodeText(node)); break; case 'Impression': ad.impressionURLTemplates.push(parserUtils.parseNodeText(node)); break; case 'Creatives': parserUtils.childrenByName(node, 'Creative').forEach(function (creativeElement) { var creativeAttributes = { id: creativeElement.getAttribute('id') || null, adId: parseCreativeAdIdAttribute(creativeElement), sequence: creativeElement.getAttribute('sequence') || null, apiFramework: creativeElement.getAttribute('apiFramework') || null }; for (var creativeTypeElementKey in creativeElement.childNodes) { var creativeTypeElement = creativeElement.childNodes[creativeTypeElementKey]; var parsedCreative = void 0; switch (creativeTypeElement.nodeName) { case 'Linear': parsedCreative = parseCreativeLinear(creativeTypeElement, creativeAttributes); if (parsedCreative) { ad.creatives.push(parsedCreative); } break; case 'NonLinearAds': parsedCreative = parseCreativeNonLinear(creativeTypeElement, creativeAttributes); if (parsedCreative) { ad.creatives.push(parsedCreative); } break; case 'CompanionAds': parsedCreative = parseCreativeCompanion(creativeTypeElement, creativeAttributes); if (parsedCreative) { ad.creatives.push(parsedCreative); } break; } } }); break; case 'Extensions': parseExtensions(ad.extensions, parserUtils.childrenByName(node, 'Extension')); break; case 'AdSystem': ad.system = { value: parserUtils.parseNodeText(node), version: node.getAttribute('version') || null }; break; case 'AdTitle': ad.title = parserUtils.parseNodeText(node); break; case 'Description': ad.description = parserUtils.parseNodeText(node); break; case 'Advertiser': ad.advertiser = parserUtils.parseNodeText(node); break; case 'Pricing': ad.pricing = { value: parserUtils.parseNodeText(node), model: node.getAttribute('model') || null, currency: node.getAttribute('currency') || null }; break; case 'Survey': ad.survey = parserUtils.parseNodeText(node); break; } } return ad; }
javascript
function parseInLine(inLineElement) { var childNodes = inLineElement.childNodes; var ad = new Ad(); ad.id = inLineElement.getAttribute('id') || null; ad.sequence = inLineElement.getAttribute('sequence') || null; for (var nodeKey in childNodes) { var node = childNodes[nodeKey]; switch (node.nodeName) { case 'Error': ad.errorURLTemplates.push(parserUtils.parseNodeText(node)); break; case 'Impression': ad.impressionURLTemplates.push(parserUtils.parseNodeText(node)); break; case 'Creatives': parserUtils.childrenByName(node, 'Creative').forEach(function (creativeElement) { var creativeAttributes = { id: creativeElement.getAttribute('id') || null, adId: parseCreativeAdIdAttribute(creativeElement), sequence: creativeElement.getAttribute('sequence') || null, apiFramework: creativeElement.getAttribute('apiFramework') || null }; for (var creativeTypeElementKey in creativeElement.childNodes) { var creativeTypeElement = creativeElement.childNodes[creativeTypeElementKey]; var parsedCreative = void 0; switch (creativeTypeElement.nodeName) { case 'Linear': parsedCreative = parseCreativeLinear(creativeTypeElement, creativeAttributes); if (parsedCreative) { ad.creatives.push(parsedCreative); } break; case 'NonLinearAds': parsedCreative = parseCreativeNonLinear(creativeTypeElement, creativeAttributes); if (parsedCreative) { ad.creatives.push(parsedCreative); } break; case 'CompanionAds': parsedCreative = parseCreativeCompanion(creativeTypeElement, creativeAttributes); if (parsedCreative) { ad.creatives.push(parsedCreative); } break; } } }); break; case 'Extensions': parseExtensions(ad.extensions, parserUtils.childrenByName(node, 'Extension')); break; case 'AdSystem': ad.system = { value: parserUtils.parseNodeText(node), version: node.getAttribute('version') || null }; break; case 'AdTitle': ad.title = parserUtils.parseNodeText(node); break; case 'Description': ad.description = parserUtils.parseNodeText(node); break; case 'Advertiser': ad.advertiser = parserUtils.parseNodeText(node); break; case 'Pricing': ad.pricing = { value: parserUtils.parseNodeText(node), model: node.getAttribute('model') || null, currency: node.getAttribute('currency') || null }; break; case 'Survey': ad.survey = parserUtils.parseNodeText(node); break; } } return ad; }
[ "function", "parseInLine", "(", "inLineElement", ")", "{", "var", "childNodes", "=", "inLineElement", ".", "childNodes", ";", "var", "ad", "=", "new", "Ad", "(", ")", ";", "ad", ".", "id", "=", "inLineElement", ".", "getAttribute", "(", "'id'", ")", "||", "null", ";", "ad", ".", "sequence", "=", "inLineElement", ".", "getAttribute", "(", "'sequence'", ")", "||", "null", ";", "for", "(", "var", "nodeKey", "in", "childNodes", ")", "{", "var", "node", "=", "childNodes", "[", "nodeKey", "]", ";", "switch", "(", "node", ".", "nodeName", ")", "{", "case", "'Error'", ":", "ad", ".", "errorURLTemplates", ".", "push", "(", "parserUtils", ".", "parseNodeText", "(", "node", ")", ")", ";", "break", ";", "case", "'Impression'", ":", "ad", ".", "impressionURLTemplates", ".", "push", "(", "parserUtils", ".", "parseNodeText", "(", "node", ")", ")", ";", "break", ";", "case", "'Creatives'", ":", "parserUtils", ".", "childrenByName", "(", "node", ",", "'Creative'", ")", ".", "forEach", "(", "function", "(", "creativeElement", ")", "{", "var", "creativeAttributes", "=", "{", "id", ":", "creativeElement", ".", "getAttribute", "(", "'id'", ")", "||", "null", ",", "adId", ":", "parseCreativeAdIdAttribute", "(", "creativeElement", ")", ",", "sequence", ":", "creativeElement", ".", "getAttribute", "(", "'sequence'", ")", "||", "null", ",", "apiFramework", ":", "creativeElement", ".", "getAttribute", "(", "'apiFramework'", ")", "||", "null", "}", ";", "for", "(", "var", "creativeTypeElementKey", "in", "creativeElement", ".", "childNodes", ")", "{", "var", "creativeTypeElement", "=", "creativeElement", ".", "childNodes", "[", "creativeTypeElementKey", "]", ";", "var", "parsedCreative", "=", "void", "0", ";", "switch", "(", "creativeTypeElement", ".", "nodeName", ")", "{", "case", "'Linear'", ":", "parsedCreative", "=", "parseCreativeLinear", "(", "creativeTypeElement", ",", "creativeAttributes", ")", ";", "if", "(", "parsedCreative", ")", "{", "ad", ".", "creatives", ".", "push", "(", "parsedCreative", ")", ";", "}", "break", ";", "case", "'NonLinearAds'", ":", "parsedCreative", "=", "parseCreativeNonLinear", "(", "creativeTypeElement", ",", "creativeAttributes", ")", ";", "if", "(", "parsedCreative", ")", "{", "ad", ".", "creatives", ".", "push", "(", "parsedCreative", ")", ";", "}", "break", ";", "case", "'CompanionAds'", ":", "parsedCreative", "=", "parseCreativeCompanion", "(", "creativeTypeElement", ",", "creativeAttributes", ")", ";", "if", "(", "parsedCreative", ")", "{", "ad", ".", "creatives", ".", "push", "(", "parsedCreative", ")", ";", "}", "break", ";", "}", "}", "}", ")", ";", "break", ";", "case", "'Extensions'", ":", "parseExtensions", "(", "ad", ".", "extensions", ",", "parserUtils", ".", "childrenByName", "(", "node", ",", "'Extension'", ")", ")", ";", "break", ";", "case", "'AdSystem'", ":", "ad", ".", "system", "=", "{", "value", ":", "parserUtils", ".", "parseNodeText", "(", "node", ")", ",", "version", ":", "node", ".", "getAttribute", "(", "'version'", ")", "||", "null", "}", ";", "break", ";", "case", "'AdTitle'", ":", "ad", ".", "title", "=", "parserUtils", ".", "parseNodeText", "(", "node", ")", ";", "break", ";", "case", "'Description'", ":", "ad", ".", "description", "=", "parserUtils", ".", "parseNodeText", "(", "node", ")", ";", "break", ";", "case", "'Advertiser'", ":", "ad", ".", "advertiser", "=", "parserUtils", ".", "parseNodeText", "(", "node", ")", ";", "break", ";", "case", "'Pricing'", ":", "ad", ".", "pricing", "=", "{", "value", ":", "parserUtils", ".", "parseNodeText", "(", "node", ")", ",", "model", ":", "node", ".", "getAttribute", "(", "'model'", ")", "||", "null", ",", "currency", ":", "node", ".", "getAttribute", "(", "'currency'", ")", "||", "null", "}", ";", "break", ";", "case", "'Survey'", ":", "ad", ".", "survey", "=", "parserUtils", ".", "parseNodeText", "(", "node", ")", ";", "break", ";", "}", "}", "return", "ad", ";", "}" ]
Parses an Inline element. @param {Object} inLineElement - The VAST Inline element to parse. @return {Ad}
[ "Parses", "an", "Inline", "element", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/dist/vast-client-node.js#L922-L1015
9,427
dailymotion/vast-client-js
dist/vast-client-node.js
parseWrapper
function parseWrapper(wrapperElement) { var ad = parseInLine(wrapperElement); var wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURI'); if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(wrapperURLElement); } else { wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURL'); if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(parserUtils.childByName(wrapperURLElement, 'URL')); } } ad.creatives.forEach(function (wrapperCreativeElement) { if (['linear', 'nonlinear'].indexOf(wrapperCreativeElement.type) !== -1) { // TrackingEvents Linear / NonLinear if (wrapperCreativeElement.trackingEvents) { if (!ad.trackingEvents) { ad.trackingEvents = {}; } if (!ad.trackingEvents[wrapperCreativeElement.type]) { ad.trackingEvents[wrapperCreativeElement.type] = {}; } var _loop = function _loop(eventName) { var urls = wrapperCreativeElement.trackingEvents[eventName]; if (!Array.isArray(ad.trackingEvents[wrapperCreativeElement.type][eventName])) { ad.trackingEvents[wrapperCreativeElement.type][eventName] = []; } urls.forEach(function (url) { ad.trackingEvents[wrapperCreativeElement.type][eventName].push(url); }); }; for (var eventName in wrapperCreativeElement.trackingEvents) { _loop(eventName); } } // ClickTracking if (wrapperCreativeElement.videoClickTrackingURLTemplates) { if (!Array.isArray(ad.videoClickTrackingURLTemplates)) { ad.videoClickTrackingURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged wrapperCreativeElement.videoClickTrackingURLTemplates.forEach(function (item) { ad.videoClickTrackingURLTemplates.push(item); }); } // ClickThrough if (wrapperCreativeElement.videoClickThroughURLTemplate) { ad.videoClickThroughURLTemplate = wrapperCreativeElement.videoClickThroughURLTemplate; } // CustomClick if (wrapperCreativeElement.videoCustomClickURLTemplates) { if (!Array.isArray(ad.videoCustomClickURLTemplates)) { ad.videoCustomClickURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged wrapperCreativeElement.videoCustomClickURLTemplates.forEach(function (item) { ad.videoCustomClickURLTemplates.push(item); }); } } }); if (ad.nextWrapperURL) { return ad; } }
javascript
function parseWrapper(wrapperElement) { var ad = parseInLine(wrapperElement); var wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURI'); if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(wrapperURLElement); } else { wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURL'); if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(parserUtils.childByName(wrapperURLElement, 'URL')); } } ad.creatives.forEach(function (wrapperCreativeElement) { if (['linear', 'nonlinear'].indexOf(wrapperCreativeElement.type) !== -1) { // TrackingEvents Linear / NonLinear if (wrapperCreativeElement.trackingEvents) { if (!ad.trackingEvents) { ad.trackingEvents = {}; } if (!ad.trackingEvents[wrapperCreativeElement.type]) { ad.trackingEvents[wrapperCreativeElement.type] = {}; } var _loop = function _loop(eventName) { var urls = wrapperCreativeElement.trackingEvents[eventName]; if (!Array.isArray(ad.trackingEvents[wrapperCreativeElement.type][eventName])) { ad.trackingEvents[wrapperCreativeElement.type][eventName] = []; } urls.forEach(function (url) { ad.trackingEvents[wrapperCreativeElement.type][eventName].push(url); }); }; for (var eventName in wrapperCreativeElement.trackingEvents) { _loop(eventName); } } // ClickTracking if (wrapperCreativeElement.videoClickTrackingURLTemplates) { if (!Array.isArray(ad.videoClickTrackingURLTemplates)) { ad.videoClickTrackingURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged wrapperCreativeElement.videoClickTrackingURLTemplates.forEach(function (item) { ad.videoClickTrackingURLTemplates.push(item); }); } // ClickThrough if (wrapperCreativeElement.videoClickThroughURLTemplate) { ad.videoClickThroughURLTemplate = wrapperCreativeElement.videoClickThroughURLTemplate; } // CustomClick if (wrapperCreativeElement.videoCustomClickURLTemplates) { if (!Array.isArray(ad.videoCustomClickURLTemplates)) { ad.videoCustomClickURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged wrapperCreativeElement.videoCustomClickURLTemplates.forEach(function (item) { ad.videoCustomClickURLTemplates.push(item); }); } } }); if (ad.nextWrapperURL) { return ad; } }
[ "function", "parseWrapper", "(", "wrapperElement", ")", "{", "var", "ad", "=", "parseInLine", "(", "wrapperElement", ")", ";", "var", "wrapperURLElement", "=", "parserUtils", ".", "childByName", "(", "wrapperElement", ",", "'VASTAdTagURI'", ")", ";", "if", "(", "wrapperURLElement", ")", "{", "ad", ".", "nextWrapperURL", "=", "parserUtils", ".", "parseNodeText", "(", "wrapperURLElement", ")", ";", "}", "else", "{", "wrapperURLElement", "=", "parserUtils", ".", "childByName", "(", "wrapperElement", ",", "'VASTAdTagURL'", ")", ";", "if", "(", "wrapperURLElement", ")", "{", "ad", ".", "nextWrapperURL", "=", "parserUtils", ".", "parseNodeText", "(", "parserUtils", ".", "childByName", "(", "wrapperURLElement", ",", "'URL'", ")", ")", ";", "}", "}", "ad", ".", "creatives", ".", "forEach", "(", "function", "(", "wrapperCreativeElement", ")", "{", "if", "(", "[", "'linear'", ",", "'nonlinear'", "]", ".", "indexOf", "(", "wrapperCreativeElement", ".", "type", ")", "!==", "-", "1", ")", "{", "// TrackingEvents Linear / NonLinear", "if", "(", "wrapperCreativeElement", ".", "trackingEvents", ")", "{", "if", "(", "!", "ad", ".", "trackingEvents", ")", "{", "ad", ".", "trackingEvents", "=", "{", "}", ";", "}", "if", "(", "!", "ad", ".", "trackingEvents", "[", "wrapperCreativeElement", ".", "type", "]", ")", "{", "ad", ".", "trackingEvents", "[", "wrapperCreativeElement", ".", "type", "]", "=", "{", "}", ";", "}", "var", "_loop", "=", "function", "_loop", "(", "eventName", ")", "{", "var", "urls", "=", "wrapperCreativeElement", ".", "trackingEvents", "[", "eventName", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "ad", ".", "trackingEvents", "[", "wrapperCreativeElement", ".", "type", "]", "[", "eventName", "]", ")", ")", "{", "ad", ".", "trackingEvents", "[", "wrapperCreativeElement", ".", "type", "]", "[", "eventName", "]", "=", "[", "]", ";", "}", "urls", ".", "forEach", "(", "function", "(", "url", ")", "{", "ad", ".", "trackingEvents", "[", "wrapperCreativeElement", ".", "type", "]", "[", "eventName", "]", ".", "push", "(", "url", ")", ";", "}", ")", ";", "}", ";", "for", "(", "var", "eventName", "in", "wrapperCreativeElement", ".", "trackingEvents", ")", "{", "_loop", "(", "eventName", ")", ";", "}", "}", "// ClickTracking", "if", "(", "wrapperCreativeElement", ".", "videoClickTrackingURLTemplates", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "ad", ".", "videoClickTrackingURLTemplates", ")", ")", "{", "ad", ".", "videoClickTrackingURLTemplates", "=", "[", "]", ";", "}", "// tmp property to save wrapper tracking URLs until they are merged", "wrapperCreativeElement", ".", "videoClickTrackingURLTemplates", ".", "forEach", "(", "function", "(", "item", ")", "{", "ad", ".", "videoClickTrackingURLTemplates", ".", "push", "(", "item", ")", ";", "}", ")", ";", "}", "// ClickThrough", "if", "(", "wrapperCreativeElement", ".", "videoClickThroughURLTemplate", ")", "{", "ad", ".", "videoClickThroughURLTemplate", "=", "wrapperCreativeElement", ".", "videoClickThroughURLTemplate", ";", "}", "// CustomClick", "if", "(", "wrapperCreativeElement", ".", "videoCustomClickURLTemplates", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "ad", ".", "videoCustomClickURLTemplates", ")", ")", "{", "ad", ".", "videoCustomClickURLTemplates", "=", "[", "]", ";", "}", "// tmp property to save wrapper tracking URLs until they are merged", "wrapperCreativeElement", ".", "videoCustomClickURLTemplates", ".", "forEach", "(", "function", "(", "item", ")", "{", "ad", ".", "videoCustomClickURLTemplates", ".", "push", "(", "item", ")", ";", "}", ")", ";", "}", "}", "}", ")", ";", "if", "(", "ad", ".", "nextWrapperURL", ")", "{", "return", "ad", ";", "}", "}" ]
Parses a Wrapper element without resolving the wrapped urls. @param {Object} wrapperElement - The VAST Wrapper element to be parsed. @return {Ad}
[ "Parses", "a", "Wrapper", "element", "without", "resolving", "the", "wrapped", "urls", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/dist/vast-client-node.js#L1022-L1089
9,428
dailymotion/vast-client-js
dist/vast-client-node.js
VASTParser
function VASTParser() { classCallCheck(this, VASTParser); var _this = possibleConstructorReturn(this, (VASTParser.__proto__ || Object.getPrototypeOf(VASTParser)).call(this)); _this.remainingAds = []; _this.parentURLs = []; _this.errorURLTemplates = []; _this.rootErrorURLTemplates = []; _this.maxWrapperDepth = null; _this.URLTemplateFilters = []; _this.fetchingOptions = {}; return _this; }
javascript
function VASTParser() { classCallCheck(this, VASTParser); var _this = possibleConstructorReturn(this, (VASTParser.__proto__ || Object.getPrototypeOf(VASTParser)).call(this)); _this.remainingAds = []; _this.parentURLs = []; _this.errorURLTemplates = []; _this.rootErrorURLTemplates = []; _this.maxWrapperDepth = null; _this.URLTemplateFilters = []; _this.fetchingOptions = {}; return _this; }
[ "function", "VASTParser", "(", ")", "{", "classCallCheck", "(", "this", ",", "VASTParser", ")", ";", "var", "_this", "=", "possibleConstructorReturn", "(", "this", ",", "(", "VASTParser", ".", "__proto__", "||", "Object", ".", "getPrototypeOf", "(", "VASTParser", ")", ")", ".", "call", "(", "this", ")", ")", ";", "_this", ".", "remainingAds", "=", "[", "]", ";", "_this", ".", "parentURLs", "=", "[", "]", ";", "_this", ".", "errorURLTemplates", "=", "[", "]", ";", "_this", ".", "rootErrorURLTemplates", "=", "[", "]", ";", "_this", ".", "maxWrapperDepth", "=", "null", ";", "_this", ".", "URLTemplateFilters", "=", "[", "]", ";", "_this", ".", "fetchingOptions", "=", "{", "}", ";", "return", "_this", ";", "}" ]
Creates an instance of VASTParser. @constructor
[ "Creates", "an", "instance", "of", "VASTParser", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/dist/vast-client-node.js#L1344-L1357
9,429
dailymotion/vast-client-js
dist/vast-client-node.js
VASTClient
function VASTClient(cappingFreeLunch, cappingMinimumTimeInterval, customStorage) { classCallCheck(this, VASTClient); this.cappingFreeLunch = cappingFreeLunch || 0; this.cappingMinimumTimeInterval = cappingMinimumTimeInterval || 0; this.defaultOptions = { withCredentials: false, timeout: 0 }; this.vastParser = new VASTParser(); this.storage = customStorage || new Storage(); // Init values if not already set if (this.lastSuccessfulAd === undefined) { this.lastSuccessfulAd = 0; } if (this.totalCalls === undefined) { this.totalCalls = 0; } if (this.totalCallsTimeout === undefined) { this.totalCallsTimeout = 0; } }
javascript
function VASTClient(cappingFreeLunch, cappingMinimumTimeInterval, customStorage) { classCallCheck(this, VASTClient); this.cappingFreeLunch = cappingFreeLunch || 0; this.cappingMinimumTimeInterval = cappingMinimumTimeInterval || 0; this.defaultOptions = { withCredentials: false, timeout: 0 }; this.vastParser = new VASTParser(); this.storage = customStorage || new Storage(); // Init values if not already set if (this.lastSuccessfulAd === undefined) { this.lastSuccessfulAd = 0; } if (this.totalCalls === undefined) { this.totalCalls = 0; } if (this.totalCallsTimeout === undefined) { this.totalCallsTimeout = 0; } }
[ "function", "VASTClient", "(", "cappingFreeLunch", ",", "cappingMinimumTimeInterval", ",", "customStorage", ")", "{", "classCallCheck", "(", "this", ",", "VASTClient", ")", ";", "this", ".", "cappingFreeLunch", "=", "cappingFreeLunch", "||", "0", ";", "this", ".", "cappingMinimumTimeInterval", "=", "cappingMinimumTimeInterval", "||", "0", ";", "this", ".", "defaultOptions", "=", "{", "withCredentials", ":", "false", ",", "timeout", ":", "0", "}", ";", "this", ".", "vastParser", "=", "new", "VASTParser", "(", ")", ";", "this", ".", "storage", "=", "customStorage", "||", "new", "Storage", "(", ")", ";", "// Init values if not already set", "if", "(", "this", ".", "lastSuccessfulAd", "===", "undefined", ")", "{", "this", ".", "lastSuccessfulAd", "=", "0", ";", "}", "if", "(", "this", ".", "totalCalls", "===", "undefined", ")", "{", "this", ".", "totalCalls", "=", "0", ";", "}", "if", "(", "this", ".", "totalCallsTimeout", "===", "undefined", ")", "{", "this", ".", "totalCallsTimeout", "=", "0", ";", "}", "}" ]
Creates an instance of VASTClient. @param {Number} cappingFreeLunch - The number of first calls to skip. @param {Number} cappingMinimumTimeInterval - The minimum time interval between two consecutive calls. @param {Storage} customStorage - A custom storage to use instead of the default one. @constructor
[ "Creates", "an", "instance", "of", "VASTClient", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/dist/vast-client-node.js#L2006-L2029
9,430
dailymotion/vast-client-js
dist/vast-client-node.js
VASTTracker
function VASTTracker(client, ad, creative) { var variation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; classCallCheck(this, VASTTracker); var _this = possibleConstructorReturn(this, (VASTTracker.__proto__ || Object.getPrototypeOf(VASTTracker)).call(this)); _this.ad = ad; _this.creative = creative; _this.variation = variation; _this.muted = false; _this.impressed = false; _this.skippable = false; _this.trackingEvents = {}; // We need to save the already triggered quartiles, in order to not trigger them again _this._alreadyTriggeredQuartiles = {}; // Tracker listeners should be notified with some events // no matter if there is a tracking URL or not _this.emitAlwaysEvents = ['creativeView', 'start', 'firstQuartile', 'midpoint', 'thirdQuartile', 'complete', 'resume', 'pause', 'rewind', 'skip', 'closeLinear', 'close']; // Duplicate the creative's trackingEvents property so we can alter it for (var eventName in _this.creative.trackingEvents) { var events$$1 = _this.creative.trackingEvents[eventName]; _this.trackingEvents[eventName] = events$$1.slice(0); } // Nonlinear and companion creatives provide some tracking information at a variation level // While linear creatives provided that at a creative level. That's why we need to // differentiate how we retrieve some tracking information. if (_this.creative instanceof CreativeLinear) { _this._initLinearTracking(); } else { _this._initVariationTracking(); } // If the tracker is associated with a client we add a listener to the start event // to update the lastSuccessfulAd property. if (client) { _this.on('start', function () { client.lastSuccessfulAd = Date.now(); }); } return _this; }
javascript
function VASTTracker(client, ad, creative) { var variation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; classCallCheck(this, VASTTracker); var _this = possibleConstructorReturn(this, (VASTTracker.__proto__ || Object.getPrototypeOf(VASTTracker)).call(this)); _this.ad = ad; _this.creative = creative; _this.variation = variation; _this.muted = false; _this.impressed = false; _this.skippable = false; _this.trackingEvents = {}; // We need to save the already triggered quartiles, in order to not trigger them again _this._alreadyTriggeredQuartiles = {}; // Tracker listeners should be notified with some events // no matter if there is a tracking URL or not _this.emitAlwaysEvents = ['creativeView', 'start', 'firstQuartile', 'midpoint', 'thirdQuartile', 'complete', 'resume', 'pause', 'rewind', 'skip', 'closeLinear', 'close']; // Duplicate the creative's trackingEvents property so we can alter it for (var eventName in _this.creative.trackingEvents) { var events$$1 = _this.creative.trackingEvents[eventName]; _this.trackingEvents[eventName] = events$$1.slice(0); } // Nonlinear and companion creatives provide some tracking information at a variation level // While linear creatives provided that at a creative level. That's why we need to // differentiate how we retrieve some tracking information. if (_this.creative instanceof CreativeLinear) { _this._initLinearTracking(); } else { _this._initVariationTracking(); } // If the tracker is associated with a client we add a listener to the start event // to update the lastSuccessfulAd property. if (client) { _this.on('start', function () { client.lastSuccessfulAd = Date.now(); }); } return _this; }
[ "function", "VASTTracker", "(", "client", ",", "ad", ",", "creative", ")", "{", "var", "variation", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "null", ";", "classCallCheck", "(", "this", ",", "VASTTracker", ")", ";", "var", "_this", "=", "possibleConstructorReturn", "(", "this", ",", "(", "VASTTracker", ".", "__proto__", "||", "Object", ".", "getPrototypeOf", "(", "VASTTracker", ")", ")", ".", "call", "(", "this", ")", ")", ";", "_this", ".", "ad", "=", "ad", ";", "_this", ".", "creative", "=", "creative", ";", "_this", ".", "variation", "=", "variation", ";", "_this", ".", "muted", "=", "false", ";", "_this", ".", "impressed", "=", "false", ";", "_this", ".", "skippable", "=", "false", ";", "_this", ".", "trackingEvents", "=", "{", "}", ";", "// We need to save the already triggered quartiles, in order to not trigger them again", "_this", ".", "_alreadyTriggeredQuartiles", "=", "{", "}", ";", "// Tracker listeners should be notified with some events", "// no matter if there is a tracking URL or not", "_this", ".", "emitAlwaysEvents", "=", "[", "'creativeView'", ",", "'start'", ",", "'firstQuartile'", ",", "'midpoint'", ",", "'thirdQuartile'", ",", "'complete'", ",", "'resume'", ",", "'pause'", ",", "'rewind'", ",", "'skip'", ",", "'closeLinear'", ",", "'close'", "]", ";", "// Duplicate the creative's trackingEvents property so we can alter it", "for", "(", "var", "eventName", "in", "_this", ".", "creative", ".", "trackingEvents", ")", "{", "var", "events$$1", "=", "_this", ".", "creative", ".", "trackingEvents", "[", "eventName", "]", ";", "_this", ".", "trackingEvents", "[", "eventName", "]", "=", "events$$1", ".", "slice", "(", "0", ")", ";", "}", "// Nonlinear and companion creatives provide some tracking information at a variation level", "// While linear creatives provided that at a creative level. That's why we need to", "// differentiate how we retrieve some tracking information.", "if", "(", "_this", ".", "creative", "instanceof", "CreativeLinear", ")", "{", "_this", ".", "_initLinearTracking", "(", ")", ";", "}", "else", "{", "_this", ".", "_initVariationTracking", "(", ")", ";", "}", "// If the tracker is associated with a client we add a listener to the start event", "// to update the lastSuccessfulAd property.", "if", "(", "client", ")", "{", "_this", ".", "on", "(", "'start'", ",", "function", "(", ")", "{", "client", ".", "lastSuccessfulAd", "=", "Date", ".", "now", "(", ")", ";", "}", ")", ";", "}", "return", "_this", ";", "}" ]
Creates an instance of VASTTracker. @param {VASTClient} client - An instance of VASTClient that can be updated by the tracker. [optional] @param {Ad} ad - The ad to track. @param {Creative} creative - The creative to track. @param {CompanionAd|NonLinearAd} [variation=null] - An optional variation of the creative. @constructor
[ "Creates", "an", "instance", "of", "VASTTracker", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/dist/vast-client-node.js#L2169-L2211
9,431
dailymotion/vast-client-js
src/parser/ad_parser.js
parseExtensions
function parseExtensions(collection, extensions) { extensions.forEach(extNode => { const ext = new AdExtension(); const extNodeAttrs = extNode.attributes; const childNodes = extNode.childNodes; if (extNode.attributes) { for (const extNodeAttrKey in extNodeAttrs) { const extNodeAttr = extNodeAttrs[extNodeAttrKey]; if (extNodeAttr.nodeName && extNodeAttr.nodeValue) { ext.attributes[extNodeAttr.nodeName] = extNodeAttr.nodeValue; } } } for (const childNodeKey in childNodes) { const childNode = childNodes[childNodeKey]; const txt = parserUtils.parseNodeText(childNode); // ignore comments / empty value if (childNode.nodeName !== '#comment' && txt !== '') { const extChild = new AdExtensionChild(); extChild.name = childNode.nodeName; extChild.value = txt; if (childNode.attributes) { const childNodeAttributes = childNode.attributes; for (const extChildNodeAttrKey in childNodeAttributes) { const extChildNodeAttr = childNodeAttributes[extChildNodeAttrKey]; extChild.attributes[extChildNodeAttr.nodeName] = extChildNodeAttr.nodeValue; } } ext.children.push(extChild); } } collection.push(ext); }); }
javascript
function parseExtensions(collection, extensions) { extensions.forEach(extNode => { const ext = new AdExtension(); const extNodeAttrs = extNode.attributes; const childNodes = extNode.childNodes; if (extNode.attributes) { for (const extNodeAttrKey in extNodeAttrs) { const extNodeAttr = extNodeAttrs[extNodeAttrKey]; if (extNodeAttr.nodeName && extNodeAttr.nodeValue) { ext.attributes[extNodeAttr.nodeName] = extNodeAttr.nodeValue; } } } for (const childNodeKey in childNodes) { const childNode = childNodes[childNodeKey]; const txt = parserUtils.parseNodeText(childNode); // ignore comments / empty value if (childNode.nodeName !== '#comment' && txt !== '') { const extChild = new AdExtensionChild(); extChild.name = childNode.nodeName; extChild.value = txt; if (childNode.attributes) { const childNodeAttributes = childNode.attributes; for (const extChildNodeAttrKey in childNodeAttributes) { const extChildNodeAttr = childNodeAttributes[extChildNodeAttrKey]; extChild.attributes[extChildNodeAttr.nodeName] = extChildNodeAttr.nodeValue; } } ext.children.push(extChild); } } collection.push(ext); }); }
[ "function", "parseExtensions", "(", "collection", ",", "extensions", ")", "{", "extensions", ".", "forEach", "(", "extNode", "=>", "{", "const", "ext", "=", "new", "AdExtension", "(", ")", ";", "const", "extNodeAttrs", "=", "extNode", ".", "attributes", ";", "const", "childNodes", "=", "extNode", ".", "childNodes", ";", "if", "(", "extNode", ".", "attributes", ")", "{", "for", "(", "const", "extNodeAttrKey", "in", "extNodeAttrs", ")", "{", "const", "extNodeAttr", "=", "extNodeAttrs", "[", "extNodeAttrKey", "]", ";", "if", "(", "extNodeAttr", ".", "nodeName", "&&", "extNodeAttr", ".", "nodeValue", ")", "{", "ext", ".", "attributes", "[", "extNodeAttr", ".", "nodeName", "]", "=", "extNodeAttr", ".", "nodeValue", ";", "}", "}", "}", "for", "(", "const", "childNodeKey", "in", "childNodes", ")", "{", "const", "childNode", "=", "childNodes", "[", "childNodeKey", "]", ";", "const", "txt", "=", "parserUtils", ".", "parseNodeText", "(", "childNode", ")", ";", "// ignore comments / empty value", "if", "(", "childNode", ".", "nodeName", "!==", "'#comment'", "&&", "txt", "!==", "''", ")", "{", "const", "extChild", "=", "new", "AdExtensionChild", "(", ")", ";", "extChild", ".", "name", "=", "childNode", ".", "nodeName", ";", "extChild", ".", "value", "=", "txt", ";", "if", "(", "childNode", ".", "attributes", ")", "{", "const", "childNodeAttributes", "=", "childNode", ".", "attributes", ";", "for", "(", "const", "extChildNodeAttrKey", "in", "childNodeAttributes", ")", "{", "const", "extChildNodeAttr", "=", "childNodeAttributes", "[", "extChildNodeAttrKey", "]", ";", "extChild", ".", "attributes", "[", "extChildNodeAttr", ".", "nodeName", "]", "=", "extChildNodeAttr", ".", "nodeValue", ";", "}", "}", "ext", ".", "children", ".", "push", "(", "extChild", ")", ";", "}", "}", "collection", ".", "push", "(", "ext", ")", ";", "}", ")", ";", "}" ]
Parses an array of Extension elements. @param {Array} collection - The array used to store the parsed extensions. @param {Array} extensions - The array of extensions to parse.
[ "Parses", "an", "array", "of", "Extension", "elements", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/src/parser/ad_parser.js#L238-L281
9,432
dailymotion/vast-client-js
src/util/util.js
resolveURLTemplates
function resolveURLTemplates(URLTemplates, variables = {}, options = {}) { const URLs = []; // Encode String variables, when given if (variables['ASSETURI']) { variables['ASSETURI'] = encodeURIComponentRFC3986(variables['ASSETURI']); } if (variables['CONTENTPLAYHEAD']) { variables['CONTENTPLAYHEAD'] = encodeURIComponentRFC3986( variables['CONTENTPLAYHEAD'] ); } // Set default value for invalid ERRORCODE if ( variables['ERRORCODE'] && !options.isCustomCode && !/^[0-9]{3}$/.test(variables['ERRORCODE']) ) { variables['ERRORCODE'] = 900; } // Calc random/time based macros variables['CACHEBUSTING'] = leftpad( Math.round(Math.random() * 1.0e8).toString() ); variables['TIMESTAMP'] = encodeURIComponentRFC3986(new Date().toISOString()); // RANDOM/random is not defined in VAST 3/4 as a valid macro tho it's used by some adServer (Auditude) variables['RANDOM'] = variables['random'] = variables['CACHEBUSTING']; for (const URLTemplateKey in URLTemplates) { let resolveURL = URLTemplates[URLTemplateKey]; if (typeof resolveURL !== 'string') { continue; } for (const key in variables) { const value = variables[key]; const macro1 = `[${key}]`; const macro2 = `%%${key}%%`; resolveURL = resolveURL.replace(macro1, value); resolveURL = resolveURL.replace(macro2, value); } URLs.push(resolveURL); } return URLs; }
javascript
function resolveURLTemplates(URLTemplates, variables = {}, options = {}) { const URLs = []; // Encode String variables, when given if (variables['ASSETURI']) { variables['ASSETURI'] = encodeURIComponentRFC3986(variables['ASSETURI']); } if (variables['CONTENTPLAYHEAD']) { variables['CONTENTPLAYHEAD'] = encodeURIComponentRFC3986( variables['CONTENTPLAYHEAD'] ); } // Set default value for invalid ERRORCODE if ( variables['ERRORCODE'] && !options.isCustomCode && !/^[0-9]{3}$/.test(variables['ERRORCODE']) ) { variables['ERRORCODE'] = 900; } // Calc random/time based macros variables['CACHEBUSTING'] = leftpad( Math.round(Math.random() * 1.0e8).toString() ); variables['TIMESTAMP'] = encodeURIComponentRFC3986(new Date().toISOString()); // RANDOM/random is not defined in VAST 3/4 as a valid macro tho it's used by some adServer (Auditude) variables['RANDOM'] = variables['random'] = variables['CACHEBUSTING']; for (const URLTemplateKey in URLTemplates) { let resolveURL = URLTemplates[URLTemplateKey]; if (typeof resolveURL !== 'string') { continue; } for (const key in variables) { const value = variables[key]; const macro1 = `[${key}]`; const macro2 = `%%${key}%%`; resolveURL = resolveURL.replace(macro1, value); resolveURL = resolveURL.replace(macro2, value); } URLs.push(resolveURL); } return URLs; }
[ "function", "resolveURLTemplates", "(", "URLTemplates", ",", "variables", "=", "{", "}", ",", "options", "=", "{", "}", ")", "{", "const", "URLs", "=", "[", "]", ";", "// Encode String variables, when given", "if", "(", "variables", "[", "'ASSETURI'", "]", ")", "{", "variables", "[", "'ASSETURI'", "]", "=", "encodeURIComponentRFC3986", "(", "variables", "[", "'ASSETURI'", "]", ")", ";", "}", "if", "(", "variables", "[", "'CONTENTPLAYHEAD'", "]", ")", "{", "variables", "[", "'CONTENTPLAYHEAD'", "]", "=", "encodeURIComponentRFC3986", "(", "variables", "[", "'CONTENTPLAYHEAD'", "]", ")", ";", "}", "// Set default value for invalid ERRORCODE", "if", "(", "variables", "[", "'ERRORCODE'", "]", "&&", "!", "options", ".", "isCustomCode", "&&", "!", "/", "^[0-9]{3}$", "/", ".", "test", "(", "variables", "[", "'ERRORCODE'", "]", ")", ")", "{", "variables", "[", "'ERRORCODE'", "]", "=", "900", ";", "}", "// Calc random/time based macros", "variables", "[", "'CACHEBUSTING'", "]", "=", "leftpad", "(", "Math", ".", "round", "(", "Math", ".", "random", "(", ")", "*", "1.0e8", ")", ".", "toString", "(", ")", ")", ";", "variables", "[", "'TIMESTAMP'", "]", "=", "encodeURIComponentRFC3986", "(", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ")", ";", "// RANDOM/random is not defined in VAST 3/4 as a valid macro tho it's used by some adServer (Auditude)", "variables", "[", "'RANDOM'", "]", "=", "variables", "[", "'random'", "]", "=", "variables", "[", "'CACHEBUSTING'", "]", ";", "for", "(", "const", "URLTemplateKey", "in", "URLTemplates", ")", "{", "let", "resolveURL", "=", "URLTemplates", "[", "URLTemplateKey", "]", ";", "if", "(", "typeof", "resolveURL", "!==", "'string'", ")", "{", "continue", ";", "}", "for", "(", "const", "key", "in", "variables", ")", "{", "const", "value", "=", "variables", "[", "key", "]", ";", "const", "macro1", "=", "`", "${", "key", "}", "`", ";", "const", "macro2", "=", "`", "${", "key", "}", "`", ";", "resolveURL", "=", "resolveURL", ".", "replace", "(", "macro1", ",", "value", ")", ";", "resolveURL", "=", "resolveURL", ".", "replace", "(", "macro2", ",", "value", ")", ";", "}", "URLs", ".", "push", "(", "resolveURL", ")", ";", "}", "return", "URLs", ";", "}" ]
Replace the provided URLTemplates with the given values @param {Array} URLTemplates - An array of tracking url templates. @param {Object} [variables={}] - An optional Object of parameters to be used in the tracking calls. @param {Object} [options={}] - An optional Object of options to be used in the tracking calls.
[ "Replace", "the", "provided", "URLTemplates", "with", "the", "given", "values" ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/src/util/util.js#L19-L68
9,433
dailymotion/vast-client-js
src/parser/parser_utils.js
copyNodeAttribute
function copyNodeAttribute(attributeName, nodeSource, nodeDestination) { const attributeValue = nodeSource.getAttribute(attributeName); if (attributeValue) { nodeDestination.setAttribute(attributeName, attributeValue); } }
javascript
function copyNodeAttribute(attributeName, nodeSource, nodeDestination) { const attributeValue = nodeSource.getAttribute(attributeName); if (attributeValue) { nodeDestination.setAttribute(attributeName, attributeValue); } }
[ "function", "copyNodeAttribute", "(", "attributeName", ",", "nodeSource", ",", "nodeDestination", ")", "{", "const", "attributeValue", "=", "nodeSource", ".", "getAttribute", "(", "attributeName", ")", ";", "if", "(", "attributeValue", ")", "{", "nodeDestination", ".", "setAttribute", "(", "attributeName", ",", "attributeValue", ")", ";", "}", "}" ]
Copies an attribute from a node to another. @param {String} attributeName - The name of the attribute to clone. @param {Object} nodeSource - The source node to copy the attribute from. @param {Object} nodeDestination - The destination node to copy the attribute at.
[ "Copies", "an", "attribute", "from", "a", "node", "to", "another", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/src/parser/parser_utils.js#L94-L99
9,434
dailymotion/vast-client-js
src/parser/parser_utils.js
parseDuration
function parseDuration(durationString) { if (durationString === null || typeof durationString === 'undefined') { return -1; } // Some VAST doesn't have an HH:MM:SS duration format but instead jus the number of seconds if (util.isNumeric(durationString)) { return parseInt(durationString); } const durationComponents = durationString.split(':'); if (durationComponents.length !== 3) { return -1; } const secondsAndMS = durationComponents[2].split('.'); let seconds = parseInt(secondsAndMS[0]); if (secondsAndMS.length === 2) { seconds += parseFloat(`0.${secondsAndMS[1]}`); } const minutes = parseInt(durationComponents[1] * 60); const hours = parseInt(durationComponents[0] * 60 * 60); if ( isNaN(hours) || isNaN(minutes) || isNaN(seconds) || minutes > 60 * 60 || seconds > 60 ) { return -1; } return hours + minutes + seconds; }
javascript
function parseDuration(durationString) { if (durationString === null || typeof durationString === 'undefined') { return -1; } // Some VAST doesn't have an HH:MM:SS duration format but instead jus the number of seconds if (util.isNumeric(durationString)) { return parseInt(durationString); } const durationComponents = durationString.split(':'); if (durationComponents.length !== 3) { return -1; } const secondsAndMS = durationComponents[2].split('.'); let seconds = parseInt(secondsAndMS[0]); if (secondsAndMS.length === 2) { seconds += parseFloat(`0.${secondsAndMS[1]}`); } const minutes = parseInt(durationComponents[1] * 60); const hours = parseInt(durationComponents[0] * 60 * 60); if ( isNaN(hours) || isNaN(minutes) || isNaN(seconds) || minutes > 60 * 60 || seconds > 60 ) { return -1; } return hours + minutes + seconds; }
[ "function", "parseDuration", "(", "durationString", ")", "{", "if", "(", "durationString", "===", "null", "||", "typeof", "durationString", "===", "'undefined'", ")", "{", "return", "-", "1", ";", "}", "// Some VAST doesn't have an HH:MM:SS duration format but instead jus the number of seconds", "if", "(", "util", ".", "isNumeric", "(", "durationString", ")", ")", "{", "return", "parseInt", "(", "durationString", ")", ";", "}", "const", "durationComponents", "=", "durationString", ".", "split", "(", "':'", ")", ";", "if", "(", "durationComponents", ".", "length", "!==", "3", ")", "{", "return", "-", "1", ";", "}", "const", "secondsAndMS", "=", "durationComponents", "[", "2", "]", ".", "split", "(", "'.'", ")", ";", "let", "seconds", "=", "parseInt", "(", "secondsAndMS", "[", "0", "]", ")", ";", "if", "(", "secondsAndMS", ".", "length", "===", "2", ")", "{", "seconds", "+=", "parseFloat", "(", "`", "${", "secondsAndMS", "[", "1", "]", "}", "`", ")", ";", "}", "const", "minutes", "=", "parseInt", "(", "durationComponents", "[", "1", "]", "*", "60", ")", ";", "const", "hours", "=", "parseInt", "(", "durationComponents", "[", "0", "]", "*", "60", "*", "60", ")", ";", "if", "(", "isNaN", "(", "hours", ")", "||", "isNaN", "(", "minutes", ")", "||", "isNaN", "(", "seconds", ")", "||", "minutes", ">", "60", "*", "60", "||", "seconds", ">", "60", ")", "{", "return", "-", "1", ";", "}", "return", "hours", "+", "minutes", "+", "seconds", ";", "}" ]
Parses a String duration into a Number. @param {String} durationString - The dureation represented as a string. @return {Number}
[ "Parses", "a", "String", "duration", "into", "a", "Number", "." ]
da5626fbc07b5949feb602fcea49b97df6070e61
https://github.com/dailymotion/vast-client-js/blob/da5626fbc07b5949feb602fcea49b97df6070e61/src/parser/parser_utils.js#L106-L139
9,435
nearform/node-clinic
lib/authenticate.js
loadToken
async function loadToken (url) { let tokens try { const data = await readFile(credentialsPath) tokens = JSON.parse(data) } catch (err) {} return tokens && tokens[url] }
javascript
async function loadToken (url) { let tokens try { const data = await readFile(credentialsPath) tokens = JSON.parse(data) } catch (err) {} return tokens && tokens[url] }
[ "async", "function", "loadToken", "(", "url", ")", "{", "let", "tokens", "try", "{", "const", "data", "=", "await", "readFile", "(", "credentialsPath", ")", "tokens", "=", "JSON", ".", "parse", "(", "data", ")", "}", "catch", "(", "err", ")", "{", "}", "return", "tokens", "&&", "tokens", "[", "url", "]", "}" ]
Load the JWT for an Upload Server URL.
[ "Load", "the", "JWT", "for", "an", "Upload", "Server", "URL", "." ]
7e44899f42451691bc35a7a095fd17c1065ea8e8
https://github.com/nearform/node-clinic/blob/7e44899f42451691bc35a7a095fd17c1065ea8e8/lib/authenticate.js#L29-L36
9,436
nearform/node-clinic
lib/authenticate.js
validateToken
function validateToken (token) { const header = jwt.decode(token) const now = Math.floor(Date.now() / 1000) return header && header.exp > now }
javascript
function validateToken (token) { const header = jwt.decode(token) const now = Math.floor(Date.now() / 1000) return header && header.exp > now }
[ "function", "validateToken", "(", "token", ")", "{", "const", "header", "=", "jwt", ".", "decode", "(", "token", ")", "const", "now", "=", "Math", ".", "floor", "(", "Date", ".", "now", "(", ")", "/", "1000", ")", "return", "header", "&&", "header", ".", "exp", ">", "now", "}" ]
Check that a JWT has not expired.
[ "Check", "that", "a", "JWT", "has", "not", "expired", "." ]
7e44899f42451691bc35a7a095fd17c1065ea8e8
https://github.com/nearform/node-clinic/blob/7e44899f42451691bc35a7a095fd17c1065ea8e8/lib/authenticate.js#L41-L45
9,437
nearform/node-clinic
lib/authenticate.js
validateAskPermission
function validateAskPermission (token) { const header = jwt.decode(token) return validateToken(token) && header[ASK_CLAIM_KEY] }
javascript
function validateAskPermission (token) { const header = jwt.decode(token) return validateToken(token) && header[ASK_CLAIM_KEY] }
[ "function", "validateAskPermission", "(", "token", ")", "{", "const", "header", "=", "jwt", ".", "decode", "(", "token", ")", "return", "validateToken", "(", "token", ")", "&&", "header", "[", "ASK_CLAIM_KEY", "]", "}" ]
Check that a JWT has Ask terms accepted.
[ "Check", "that", "a", "JWT", "has", "Ask", "terms", "accepted", "." ]
7e44899f42451691bc35a7a095fd17c1065ea8e8
https://github.com/nearform/node-clinic/blob/7e44899f42451691bc35a7a095fd17c1065ea8e8/lib/authenticate.js#L50-L54
9,438
nearform/node-clinic
lib/authenticate.js
getSession
async function getSession (url) { const token = await loadToken(url) if (!token) return null const header = jwt.decode(token) if (!header) return null const now = Math.floor(Date.now() / 1000) if (header.exp <= now) return null return header }
javascript
async function getSession (url) { const token = await loadToken(url) if (!token) return null const header = jwt.decode(token) if (!header) return null const now = Math.floor(Date.now() / 1000) if (header.exp <= now) return null return header }
[ "async", "function", "getSession", "(", "url", ")", "{", "const", "token", "=", "await", "loadToken", "(", "url", ")", "if", "(", "!", "token", ")", "return", "null", "const", "header", "=", "jwt", ".", "decode", "(", "token", ")", "if", "(", "!", "header", ")", "return", "null", "const", "now", "=", "Math", ".", "floor", "(", "Date", ".", "now", "(", ")", "/", "1000", ")", "if", "(", "header", ".", "exp", "<=", "now", ")", "return", "null", "return", "header", "}" ]
Get the session data for an Upload Server URL.
[ "Get", "the", "session", "data", "for", "an", "Upload", "Server", "URL", "." ]
7e44899f42451691bc35a7a095fd17c1065ea8e8
https://github.com/nearform/node-clinic/blob/7e44899f42451691bc35a7a095fd17c1065ea8e8/lib/authenticate.js#L59-L67
9,439
nearform/node-clinic
lib/authenticate.js
saveToken
async function saveToken (url, token) { let tokens try { const data = await readFile(credentialsPath) tokens = JSON.parse(data) } catch (err) {} // if it was empty or contained `null` for some reason if (typeof tokens !== 'object' || !tokens) { tokens = {} } tokens[url] = token await writeFile(credentialsPath, JSON.stringify(tokens, null, 2)) }
javascript
async function saveToken (url, token) { let tokens try { const data = await readFile(credentialsPath) tokens = JSON.parse(data) } catch (err) {} // if it was empty or contained `null` for some reason if (typeof tokens !== 'object' || !tokens) { tokens = {} } tokens[url] = token await writeFile(credentialsPath, JSON.stringify(tokens, null, 2)) }
[ "async", "function", "saveToken", "(", "url", ",", "token", ")", "{", "let", "tokens", "try", "{", "const", "data", "=", "await", "readFile", "(", "credentialsPath", ")", "tokens", "=", "JSON", ".", "parse", "(", "data", ")", "}", "catch", "(", "err", ")", "{", "}", "// if it was empty or contained `null` for some reason", "if", "(", "typeof", "tokens", "!==", "'object'", "||", "!", "tokens", ")", "{", "tokens", "=", "{", "}", "}", "tokens", "[", "url", "]", "=", "token", "await", "writeFile", "(", "credentialsPath", ",", "JSON", ".", "stringify", "(", "tokens", ",", "null", ",", "2", ")", ")", "}" ]
Store the JWT for an Upload Server URL in the credentials file.
[ "Store", "the", "JWT", "for", "an", "Upload", "Server", "URL", "in", "the", "credentials", "file", "." ]
7e44899f42451691bc35a7a095fd17c1065ea8e8
https://github.com/nearform/node-clinic/blob/7e44899f42451691bc35a7a095fd17c1065ea8e8/lib/authenticate.js#L72-L87
9,440
squarefeet/ShaderParticleEngine
build/SPE.js
function( arg, type, defaultValue ) { 'use strict'; // If the argument being checked is an array, loop through // it and ensure all the values are of the correct type, // falling back to the defaultValue if any aren't. if ( Array.isArray( arg ) ) { for ( var i = arg.length - 1; i >= 0; --i ) { if ( typeof arg[ i ] !== type ) { return defaultValue; } } return arg; } // If the arg isn't an array then just fallback to // checking the type. return this.ensureTypedArg( arg, type, defaultValue ); }
javascript
function( arg, type, defaultValue ) { 'use strict'; // If the argument being checked is an array, loop through // it and ensure all the values are of the correct type, // falling back to the defaultValue if any aren't. if ( Array.isArray( arg ) ) { for ( var i = arg.length - 1; i >= 0; --i ) { if ( typeof arg[ i ] !== type ) { return defaultValue; } } return arg; } // If the arg isn't an array then just fallback to // checking the type. return this.ensureTypedArg( arg, type, defaultValue ); }
[ "function", "(", "arg", ",", "type", ",", "defaultValue", ")", "{", "'use strict'", ";", "// If the argument being checked is an array, loop through", "// it and ensure all the values are of the correct type,", "// falling back to the defaultValue if any aren't.", "if", "(", "Array", ".", "isArray", "(", "arg", ")", ")", "{", "for", "(", "var", "i", "=", "arg", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "if", "(", "typeof", "arg", "[", "i", "]", "!==", "type", ")", "{", "return", "defaultValue", ";", "}", "}", "return", "arg", ";", "}", "// If the arg isn't an array then just fallback to", "// checking the type.", "return", "this", ".", "ensureTypedArg", "(", "arg", ",", "type", ",", "defaultValue", ")", ";", "}" ]
Given an array of values, a type, and a default value, ensure the given array's contents ALL adhere to the provided type, returning the default value if type check fails. If the given value to check isn't an Array, delegates to SPE.utils.ensureTypedArg. @param {Array|boolean|string|number|object} arg The array of values to check type of. @param {String} type The type that should be adhered to. @param {(boolean|string|number|object)} defaultValue A default fallback value. @return {(boolean|string|number|object)} The given value if type check passes, or the default value if it fails.
[ "Given", "an", "array", "of", "values", "a", "type", "and", "a", "default", "value", "ensure", "the", "given", "array", "s", "contents", "ALL", "adhere", "to", "the", "provided", "type", "returning", "the", "default", "value", "if", "type", "check", "fails", "." ]
ecc2886ce952d8f0ae0739f031bead671445f8a9
https://github.com/squarefeet/ShaderParticleEngine/blob/ecc2886ce952d8f0ae0739f031bead671445f8a9/build/SPE.js#L1164-L1183
9,441
squarefeet/ShaderParticleEngine
build/SPE.js
function( arg, instance, defaultValue ) { 'use strict'; // If the argument being checked is an array, loop through // it and ensure all the values are of the correct type, // falling back to the defaultValue if any aren't. if ( Array.isArray( arg ) ) { for ( var i = arg.length - 1; i >= 0; --i ) { if ( instance !== undefined && arg[ i ] instanceof instance === false ) { return defaultValue; } } return arg; } // If the arg isn't an array then just fallback to // checking the type. return this.ensureInstanceOf( arg, instance, defaultValue ); }
javascript
function( arg, instance, defaultValue ) { 'use strict'; // If the argument being checked is an array, loop through // it and ensure all the values are of the correct type, // falling back to the defaultValue if any aren't. if ( Array.isArray( arg ) ) { for ( var i = arg.length - 1; i >= 0; --i ) { if ( instance !== undefined && arg[ i ] instanceof instance === false ) { return defaultValue; } } return arg; } // If the arg isn't an array then just fallback to // checking the type. return this.ensureInstanceOf( arg, instance, defaultValue ); }
[ "function", "(", "arg", ",", "instance", ",", "defaultValue", ")", "{", "'use strict'", ";", "// If the argument being checked is an array, loop through", "// it and ensure all the values are of the correct type,", "// falling back to the defaultValue if any aren't.", "if", "(", "Array", ".", "isArray", "(", "arg", ")", ")", "{", "for", "(", "var", "i", "=", "arg", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "if", "(", "instance", "!==", "undefined", "&&", "arg", "[", "i", "]", "instanceof", "instance", "===", "false", ")", "{", "return", "defaultValue", ";", "}", "}", "return", "arg", ";", "}", "// If the arg isn't an array then just fallback to", "// checking the type.", "return", "this", ".", "ensureInstanceOf", "(", "arg", ",", "instance", ",", "defaultValue", ")", ";", "}" ]
Given an array of values, ensure the instances of all items in the array matches the given instance constructor falling back to a default value if the check fails. If given value isn't an Array, delegates to `SPE.utils.ensureInstanceOf`. @param {Array|Object} arg The value to perform the instanceof check on. @param {Function} instance The constructor of the instance to check against. @param {Object} defaultValue A default fallback value if instance check fails @return {Object} The given value if type check passes, or the default value if it fails.
[ "Given", "an", "array", "of", "values", "ensure", "the", "instances", "of", "all", "items", "in", "the", "array", "matches", "the", "given", "instance", "constructor", "falling", "back", "to", "a", "default", "value", "if", "the", "check", "fails", "." ]
ecc2886ce952d8f0ae0739f031bead671445f8a9
https://github.com/squarefeet/ShaderParticleEngine/blob/ecc2886ce952d8f0ae0739f031bead671445f8a9/build/SPE.js#L1216-L1235
9,442
squarefeet/ShaderParticleEngine
build/SPE.js
function( value, randomise ) { 'use strict'; var epsilon = 0.00001, result = value; result = randomise ? Math.random() * epsilon * 10 : epsilon; if ( value < 0 && value > -epsilon ) { result = -result; } // if ( value === 0 ) { // result = randomise ? Math.random() * epsilon * 10 : epsilon; // } // else if ( value > 0 && value < epsilon ) { // result = randomise ? Math.random() * epsilon * 10 : epsilon; // } // else if ( value < 0 && value > -epsilon ) { // result = -( randomise ? Math.random() * epsilon * 10 : epsilon ); // } return result; }
javascript
function( value, randomise ) { 'use strict'; var epsilon = 0.00001, result = value; result = randomise ? Math.random() * epsilon * 10 : epsilon; if ( value < 0 && value > -epsilon ) { result = -result; } // if ( value === 0 ) { // result = randomise ? Math.random() * epsilon * 10 : epsilon; // } // else if ( value > 0 && value < epsilon ) { // result = randomise ? Math.random() * epsilon * 10 : epsilon; // } // else if ( value < 0 && value > -epsilon ) { // result = -( randomise ? Math.random() * epsilon * 10 : epsilon ); // } return result; }
[ "function", "(", "value", ",", "randomise", ")", "{", "'use strict'", ";", "var", "epsilon", "=", "0.00001", ",", "result", "=", "value", ";", "result", "=", "randomise", "?", "Math", ".", "random", "(", ")", "*", "epsilon", "*", "10", ":", "epsilon", ";", "if", "(", "value", "<", "0", "&&", "value", ">", "-", "epsilon", ")", "{", "result", "=", "-", "result", ";", "}", "// if ( value === 0 ) {", "// result = randomise ? Math.random() * epsilon * 10 : epsilon;", "// }", "// else if ( value > 0 && value < epsilon ) {", "// result = randomise ? Math.random() * epsilon * 10 : epsilon;", "// }", "// else if ( value < 0 && value > -epsilon ) {", "// result = -( randomise ? Math.random() * epsilon * 10 : epsilon );", "// }", "return", "result", ";", "}" ]
If the given value is less than the epsilon value, then return a randomised epsilon value if specified, or just the epsilon value if not. Works for negative numbers as well as positive. @param {Number} value The value to perform the operation on. @param {Boolean} randomise Whether the value should be randomised. @return {Number} The result of the operation.
[ "If", "the", "given", "value", "is", "less", "than", "the", "epsilon", "value", "then", "return", "a", "randomised", "epsilon", "value", "if", "specified", "or", "just", "the", "epsilon", "value", "if", "not", ".", "Works", "for", "negative", "numbers", "as", "well", "as", "positive", "." ]
ecc2886ce952d8f0ae0739f031bead671445f8a9
https://github.com/squarefeet/ShaderParticleEngine/blob/ecc2886ce952d8f0ae0739f031bead671445f8a9/build/SPE.js#L1337-L1360
9,443
squarefeet/ShaderParticleEngine
build/SPE.js
function( start, end, delta ) { 'use strict'; var types = this.types, out; if ( typeof start === types.NUMBER && typeof end === types.NUMBER ) { return start + ( ( end - start ) * delta ); } else if ( start instanceof THREE.Vector2 && end instanceof THREE.Vector2 ) { out = start.clone(); out.x = this.lerp( start.x, end.x, delta ); out.y = this.lerp( start.y, end.y, delta ); return out; } else if ( start instanceof THREE.Vector3 && end instanceof THREE.Vector3 ) { out = start.clone(); out.x = this.lerp( start.x, end.x, delta ); out.y = this.lerp( start.y, end.y, delta ); out.z = this.lerp( start.z, end.z, delta ); return out; } else if ( start instanceof THREE.Vector4 && end instanceof THREE.Vector4 ) { out = start.clone(); out.x = this.lerp( start.x, end.x, delta ); out.y = this.lerp( start.y, end.y, delta ); out.z = this.lerp( start.z, end.z, delta ); out.w = this.lerp( start.w, end.w, delta ); return out; } else if ( start instanceof THREE.Color && end instanceof THREE.Color ) { out = start.clone(); out.r = this.lerp( start.r, end.r, delta ); out.g = this.lerp( start.g, end.g, delta ); out.b = this.lerp( start.b, end.b, delta ); return out; } else { console.warn( 'Invalid argument types, or argument types do not match:', start, end ); } }
javascript
function( start, end, delta ) { 'use strict'; var types = this.types, out; if ( typeof start === types.NUMBER && typeof end === types.NUMBER ) { return start + ( ( end - start ) * delta ); } else if ( start instanceof THREE.Vector2 && end instanceof THREE.Vector2 ) { out = start.clone(); out.x = this.lerp( start.x, end.x, delta ); out.y = this.lerp( start.y, end.y, delta ); return out; } else if ( start instanceof THREE.Vector3 && end instanceof THREE.Vector3 ) { out = start.clone(); out.x = this.lerp( start.x, end.x, delta ); out.y = this.lerp( start.y, end.y, delta ); out.z = this.lerp( start.z, end.z, delta ); return out; } else if ( start instanceof THREE.Vector4 && end instanceof THREE.Vector4 ) { out = start.clone(); out.x = this.lerp( start.x, end.x, delta ); out.y = this.lerp( start.y, end.y, delta ); out.z = this.lerp( start.z, end.z, delta ); out.w = this.lerp( start.w, end.w, delta ); return out; } else if ( start instanceof THREE.Color && end instanceof THREE.Color ) { out = start.clone(); out.r = this.lerp( start.r, end.r, delta ); out.g = this.lerp( start.g, end.g, delta ); out.b = this.lerp( start.b, end.b, delta ); return out; } else { console.warn( 'Invalid argument types, or argument types do not match:', start, end ); } }
[ "function", "(", "start", ",", "end", ",", "delta", ")", "{", "'use strict'", ";", "var", "types", "=", "this", ".", "types", ",", "out", ";", "if", "(", "typeof", "start", "===", "types", ".", "NUMBER", "&&", "typeof", "end", "===", "types", ".", "NUMBER", ")", "{", "return", "start", "+", "(", "(", "end", "-", "start", ")", "*", "delta", ")", ";", "}", "else", "if", "(", "start", "instanceof", "THREE", ".", "Vector2", "&&", "end", "instanceof", "THREE", ".", "Vector2", ")", "{", "out", "=", "start", ".", "clone", "(", ")", ";", "out", ".", "x", "=", "this", ".", "lerp", "(", "start", ".", "x", ",", "end", ".", "x", ",", "delta", ")", ";", "out", ".", "y", "=", "this", ".", "lerp", "(", "start", ".", "y", ",", "end", ".", "y", ",", "delta", ")", ";", "return", "out", ";", "}", "else", "if", "(", "start", "instanceof", "THREE", ".", "Vector3", "&&", "end", "instanceof", "THREE", ".", "Vector3", ")", "{", "out", "=", "start", ".", "clone", "(", ")", ";", "out", ".", "x", "=", "this", ".", "lerp", "(", "start", ".", "x", ",", "end", ".", "x", ",", "delta", ")", ";", "out", ".", "y", "=", "this", ".", "lerp", "(", "start", ".", "y", ",", "end", ".", "y", ",", "delta", ")", ";", "out", ".", "z", "=", "this", ".", "lerp", "(", "start", ".", "z", ",", "end", ".", "z", ",", "delta", ")", ";", "return", "out", ";", "}", "else", "if", "(", "start", "instanceof", "THREE", ".", "Vector4", "&&", "end", "instanceof", "THREE", ".", "Vector4", ")", "{", "out", "=", "start", ".", "clone", "(", ")", ";", "out", ".", "x", "=", "this", ".", "lerp", "(", "start", ".", "x", ",", "end", ".", "x", ",", "delta", ")", ";", "out", ".", "y", "=", "this", ".", "lerp", "(", "start", ".", "y", ",", "end", ".", "y", ",", "delta", ")", ";", "out", ".", "z", "=", "this", ".", "lerp", "(", "start", ".", "z", ",", "end", ".", "z", ",", "delta", ")", ";", "out", ".", "w", "=", "this", ".", "lerp", "(", "start", ".", "w", ",", "end", ".", "w", ",", "delta", ")", ";", "return", "out", ";", "}", "else", "if", "(", "start", "instanceof", "THREE", ".", "Color", "&&", "end", "instanceof", "THREE", ".", "Color", ")", "{", "out", "=", "start", ".", "clone", "(", ")", ";", "out", ".", "r", "=", "this", ".", "lerp", "(", "start", ".", "r", ",", "end", ".", "r", ",", "delta", ")", ";", "out", ".", "g", "=", "this", ".", "lerp", "(", "start", ".", "g", ",", "end", ".", "g", ",", "delta", ")", ";", "out", ".", "b", "=", "this", ".", "lerp", "(", "start", ".", "b", ",", "end", ".", "b", ",", "delta", ")", ";", "return", "out", ";", "}", "else", "{", "console", ".", "warn", "(", "'Invalid argument types, or argument types do not match:'", ",", "start", ",", "end", ")", ";", "}", "}" ]
Linearly interpolates two values of various types. The given values must be of the same type for the interpolation to work. @param {(number|Object)} start The start value of the lerp. @param {(number|object)} end The end value of the lerp. @param {Number} delta The delta posiiton of the lerp operation. Ideally between 0 and 1 (inclusive). @return {(number|object|undefined)} The result of the operation. Result will be undefined if the start and end arguments aren't a supported type, or if their types do not match.
[ "Linearly", "interpolates", "two", "values", "of", "various", "types", ".", "The", "given", "values", "must", "be", "of", "the", "same", "type", "for", "the", "interpolation", "to", "work", "." ]
ecc2886ce952d8f0ae0739f031bead671445f8a9
https://github.com/squarefeet/ShaderParticleEngine/blob/ecc2886ce952d8f0ae0739f031bead671445f8a9/build/SPE.js#L1372-L1412
9,444
squarefeet/ShaderParticleEngine
build/SPE.js
function( n, multiple ) { 'use strict'; var remainder = 0; if ( multiple === 0 ) { return n; } remainder = Math.abs( n ) % multiple; if ( remainder === 0 ) { return n; } if ( n < 0 ) { return -( Math.abs( n ) - remainder ); } return n + multiple - remainder; }
javascript
function( n, multiple ) { 'use strict'; var remainder = 0; if ( multiple === 0 ) { return n; } remainder = Math.abs( n ) % multiple; if ( remainder === 0 ) { return n; } if ( n < 0 ) { return -( Math.abs( n ) - remainder ); } return n + multiple - remainder; }
[ "function", "(", "n", ",", "multiple", ")", "{", "'use strict'", ";", "var", "remainder", "=", "0", ";", "if", "(", "multiple", "===", "0", ")", "{", "return", "n", ";", "}", "remainder", "=", "Math", ".", "abs", "(", "n", ")", "%", "multiple", ";", "if", "(", "remainder", "===", "0", ")", "{", "return", "n", ";", "}", "if", "(", "n", "<", "0", ")", "{", "return", "-", "(", "Math", ".", "abs", "(", "n", ")", "-", "remainder", ")", ";", "}", "return", "n", "+", "multiple", "-", "remainder", ";", "}" ]
Rounds a number to a nearest multiple. @param {Number} n The number to round. @param {Number} multiple The multiple to round to. @return {Number} The result of the round operation.
[ "Rounds", "a", "number", "to", "a", "nearest", "multiple", "." ]
ecc2886ce952d8f0ae0739f031bead671445f8a9
https://github.com/squarefeet/ShaderParticleEngine/blob/ecc2886ce952d8f0ae0739f031bead671445f8a9/build/SPE.js#L1433-L1453
9,445
squarefeet/ShaderParticleEngine
build/SPE.js
function( attribute, index, base, radius, radiusSpread, radiusScale, radiusSpreadClamp, distributionClamp ) { 'use strict'; var depth = 2 * Math.random() - 1, t = 6.2832 * Math.random(), r = Math.sqrt( 1 - depth * depth ), rand = this.randomFloat( radius, radiusSpread ), x = 0, y = 0, z = 0; if ( radiusSpreadClamp ) { rand = Math.round( rand / radiusSpreadClamp ) * radiusSpreadClamp; } // Set position on sphere x = r * Math.cos( t ) * rand; y = r * Math.sin( t ) * rand; z = depth * rand; // Apply radius scale to this position x *= radiusScale.x; y *= radiusScale.y; z *= radiusScale.z; // Translate to the base position. x += base.x; y += base.y; z += base.z; // Set the values in the typed array. attribute.typedArray.setVec3Components( index, x, y, z ); }
javascript
function( attribute, index, base, radius, radiusSpread, radiusScale, radiusSpreadClamp, distributionClamp ) { 'use strict'; var depth = 2 * Math.random() - 1, t = 6.2832 * Math.random(), r = Math.sqrt( 1 - depth * depth ), rand = this.randomFloat( radius, radiusSpread ), x = 0, y = 0, z = 0; if ( radiusSpreadClamp ) { rand = Math.round( rand / radiusSpreadClamp ) * radiusSpreadClamp; } // Set position on sphere x = r * Math.cos( t ) * rand; y = r * Math.sin( t ) * rand; z = depth * rand; // Apply radius scale to this position x *= radiusScale.x; y *= radiusScale.y; z *= radiusScale.z; // Translate to the base position. x += base.x; y += base.y; z += base.z; // Set the values in the typed array. attribute.typedArray.setVec3Components( index, x, y, z ); }
[ "function", "(", "attribute", ",", "index", ",", "base", ",", "radius", ",", "radiusSpread", ",", "radiusScale", ",", "radiusSpreadClamp", ",", "distributionClamp", ")", "{", "'use strict'", ";", "var", "depth", "=", "2", "*", "Math", ".", "random", "(", ")", "-", "1", ",", "t", "=", "6.2832", "*", "Math", ".", "random", "(", ")", ",", "r", "=", "Math", ".", "sqrt", "(", "1", "-", "depth", "*", "depth", ")", ",", "rand", "=", "this", ".", "randomFloat", "(", "radius", ",", "radiusSpread", ")", ",", "x", "=", "0", ",", "y", "=", "0", ",", "z", "=", "0", ";", "if", "(", "radiusSpreadClamp", ")", "{", "rand", "=", "Math", ".", "round", "(", "rand", "/", "radiusSpreadClamp", ")", "*", "radiusSpreadClamp", ";", "}", "// Set position on sphere", "x", "=", "r", "*", "Math", ".", "cos", "(", "t", ")", "*", "rand", ";", "y", "=", "r", "*", "Math", ".", "sin", "(", "t", ")", "*", "rand", ";", "z", "=", "depth", "*", "rand", ";", "// Apply radius scale to this position", "x", "*=", "radiusScale", ".", "x", ";", "y", "*=", "radiusScale", ".", "y", ";", "z", "*=", "radiusScale", ".", "z", ";", "// Translate to the base position.", "x", "+=", "base", ".", "x", ";", "y", "+=", "base", ".", "y", ";", "z", "+=", "base", ".", "z", ";", "// Set the values in the typed array.", "attribute", ".", "typedArray", ".", "setVec3Components", "(", "index", ",", "x", ",", "y", ",", "z", ")", ";", "}" ]
Assigns a random vector 3 value to an SPE.ShaderAttribute instance, projecting the given values onto a sphere. @param {Object} attribute The instance of SPE.ShaderAttribute to save the result to. @param {Number} index The offset in the attribute's TypedArray to save the result from. @param {Object} base THREE.Vector3 instance describing the origin of the transform. @param {Number} radius The radius of the sphere to project onto. @param {Number} radiusSpread The amount of randomness to apply to the projection result @param {Object} radiusScale THREE.Vector3 instance describing the scale of each axis of the sphere. @param {Number} radiusSpreadClamp What numeric multiple the projected value should be clamped to.
[ "Assigns", "a", "random", "vector", "3", "value", "to", "an", "SPE", ".", "ShaderAttribute", "instance", "projecting", "the", "given", "values", "onto", "a", "sphere", "." ]
ecc2886ce952d8f0ae0739f031bead671445f8a9
https://github.com/squarefeet/ShaderParticleEngine/blob/ecc2886ce952d8f0ae0739f031bead671445f8a9/build/SPE.js#L1611-L1648
9,446
vitaly-t/pg-promise
lib/database.js
taskProcessor
function taskProcessor(params, isTX) { if (typeof params.cb !== 'function') { return $p.reject(new TypeError('Callback function is required.')); } if (params.options.reusable) { return config.$npm.task.callback(obj.ctx, obj, params.cb, config); } const taskCtx = ctx.clone(); // task context object; if (isTX) { taskCtx.txLevel = taskCtx.txLevel >= 0 ? (taskCtx.txLevel + 1) : 0; } taskCtx.inTransaction = taskCtx.txLevel >= 0; taskCtx.level = taskCtx.level >= 0 ? (taskCtx.level + 1) : 0; taskCtx.cb = params.cb; // callback function; taskCtx.mode = params.options.mode; // transaction mode; if (this !== obj) { taskCtx.context = this; // calling context object; } const tsk = new config.$npm.task.Task(taskCtx, params.options.tag, isTX, config); taskCtx.taskCtx = tsk.ctx; extend(taskCtx, tsk); if (taskCtx.db) { // reuse existing connection; npm.utils.addReadProp(tsk.ctx, 'useCount', taskCtx.db.useCount); return config.$npm.task.execute(taskCtx, tsk, isTX, config); } // connection required; return config.$npm.connect.pool(taskCtx, dbThis) .then(db => { taskCtx.connect(db); npm.utils.addReadProp(tsk.ctx, 'useCount', db.useCount); return config.$npm.task.execute(taskCtx, tsk, isTX, config); }) .then(data => { taskCtx.disconnect(); return data; }) .catch(error => { taskCtx.disconnect(); return $p.reject(error); }); }
javascript
function taskProcessor(params, isTX) { if (typeof params.cb !== 'function') { return $p.reject(new TypeError('Callback function is required.')); } if (params.options.reusable) { return config.$npm.task.callback(obj.ctx, obj, params.cb, config); } const taskCtx = ctx.clone(); // task context object; if (isTX) { taskCtx.txLevel = taskCtx.txLevel >= 0 ? (taskCtx.txLevel + 1) : 0; } taskCtx.inTransaction = taskCtx.txLevel >= 0; taskCtx.level = taskCtx.level >= 0 ? (taskCtx.level + 1) : 0; taskCtx.cb = params.cb; // callback function; taskCtx.mode = params.options.mode; // transaction mode; if (this !== obj) { taskCtx.context = this; // calling context object; } const tsk = new config.$npm.task.Task(taskCtx, params.options.tag, isTX, config); taskCtx.taskCtx = tsk.ctx; extend(taskCtx, tsk); if (taskCtx.db) { // reuse existing connection; npm.utils.addReadProp(tsk.ctx, 'useCount', taskCtx.db.useCount); return config.$npm.task.execute(taskCtx, tsk, isTX, config); } // connection required; return config.$npm.connect.pool(taskCtx, dbThis) .then(db => { taskCtx.connect(db); npm.utils.addReadProp(tsk.ctx, 'useCount', db.useCount); return config.$npm.task.execute(taskCtx, tsk, isTX, config); }) .then(data => { taskCtx.disconnect(); return data; }) .catch(error => { taskCtx.disconnect(); return $p.reject(error); }); }
[ "function", "taskProcessor", "(", "params", ",", "isTX", ")", "{", "if", "(", "typeof", "params", ".", "cb", "!==", "'function'", ")", "{", "return", "$p", ".", "reject", "(", "new", "TypeError", "(", "'Callback function is required.'", ")", ")", ";", "}", "if", "(", "params", ".", "options", ".", "reusable", ")", "{", "return", "config", ".", "$npm", ".", "task", ".", "callback", "(", "obj", ".", "ctx", ",", "obj", ",", "params", ".", "cb", ",", "config", ")", ";", "}", "const", "taskCtx", "=", "ctx", ".", "clone", "(", ")", ";", "// task context object;", "if", "(", "isTX", ")", "{", "taskCtx", ".", "txLevel", "=", "taskCtx", ".", "txLevel", ">=", "0", "?", "(", "taskCtx", ".", "txLevel", "+", "1", ")", ":", "0", ";", "}", "taskCtx", ".", "inTransaction", "=", "taskCtx", ".", "txLevel", ">=", "0", ";", "taskCtx", ".", "level", "=", "taskCtx", ".", "level", ">=", "0", "?", "(", "taskCtx", ".", "level", "+", "1", ")", ":", "0", ";", "taskCtx", ".", "cb", "=", "params", ".", "cb", ";", "// callback function;", "taskCtx", ".", "mode", "=", "params", ".", "options", ".", "mode", ";", "// transaction mode;", "if", "(", "this", "!==", "obj", ")", "{", "taskCtx", ".", "context", "=", "this", ";", "// calling context object;", "}", "const", "tsk", "=", "new", "config", ".", "$npm", ".", "task", ".", "Task", "(", "taskCtx", ",", "params", ".", "options", ".", "tag", ",", "isTX", ",", "config", ")", ";", "taskCtx", ".", "taskCtx", "=", "tsk", ".", "ctx", ";", "extend", "(", "taskCtx", ",", "tsk", ")", ";", "if", "(", "taskCtx", ".", "db", ")", "{", "// reuse existing connection;", "npm", ".", "utils", ".", "addReadProp", "(", "tsk", ".", "ctx", ",", "'useCount'", ",", "taskCtx", ".", "db", ".", "useCount", ")", ";", "return", "config", ".", "$npm", ".", "task", ".", "execute", "(", "taskCtx", ",", "tsk", ",", "isTX", ",", "config", ")", ";", "}", "// connection required;", "return", "config", ".", "$npm", ".", "connect", ".", "pool", "(", "taskCtx", ",", "dbThis", ")", ".", "then", "(", "db", "=>", "{", "taskCtx", ".", "connect", "(", "db", ")", ";", "npm", ".", "utils", ".", "addReadProp", "(", "tsk", ".", "ctx", ",", "'useCount'", ",", "db", ".", "useCount", ")", ";", "return", "config", ".", "$npm", ".", "task", ".", "execute", "(", "taskCtx", ",", "tsk", ",", "isTX", ",", "config", ")", ";", "}", ")", ".", "then", "(", "data", "=>", "{", "taskCtx", ".", "disconnect", "(", ")", ";", "return", "data", ";", "}", ")", ".", "catch", "(", "error", "=>", "{", "taskCtx", ".", "disconnect", "(", ")", ";", "return", "$p", ".", "reject", "(", "error", ")", ";", "}", ")", ";", "}" ]
Task method; Resolves with result from the callback function;
[ "Task", "method", ";", "Resolves", "with", "result", "from", "the", "callback", "function", ";" ]
a3ccf5a7fb14425c34892b869cb5502b2847180e
https://github.com/vitaly-t/pg-promise/blob/a3ccf5a7fb14425c34892b869cb5502b2847180e/lib/database.js#L1551-L1598
9,447
vitaly-t/pg-promise
lib/task.js
update
function update(start, success, result) { const c = ctx.ctx; if (start) { npm.utils.addReadProp(c, 'start', new Date()); } else { c.finish = new Date(); c.success = success; c.result = result; c.duration = c.finish - c.start; npm.utils.lock(c, true); } (isTX ? npm.events.transact : npm.events.task)(ctx.options, { client: ctx.db && ctx.db.client, // loss of connectivity is possible at this point dc: ctx.dc, ctx: c }); }
javascript
function update(start, success, result) { const c = ctx.ctx; if (start) { npm.utils.addReadProp(c, 'start', new Date()); } else { c.finish = new Date(); c.success = success; c.result = result; c.duration = c.finish - c.start; npm.utils.lock(c, true); } (isTX ? npm.events.transact : npm.events.task)(ctx.options, { client: ctx.db && ctx.db.client, // loss of connectivity is possible at this point dc: ctx.dc, ctx: c }); }
[ "function", "update", "(", "start", ",", "success", ",", "result", ")", "{", "const", "c", "=", "ctx", ".", "ctx", ";", "if", "(", "start", ")", "{", "npm", ".", "utils", ".", "addReadProp", "(", "c", ",", "'start'", ",", "new", "Date", "(", ")", ")", ";", "}", "else", "{", "c", ".", "finish", "=", "new", "Date", "(", ")", ";", "c", ".", "success", "=", "success", ";", "c", ".", "result", "=", "result", ";", "c", ".", "duration", "=", "c", ".", "finish", "-", "c", ".", "start", ";", "npm", ".", "utils", ".", "lock", "(", "c", ",", "true", ")", ";", "}", "(", "isTX", "?", "npm", ".", "events", ".", "transact", ":", "npm", ".", "events", ".", "task", ")", "(", "ctx", ".", "options", ",", "{", "client", ":", "ctx", ".", "db", "&&", "ctx", ".", "db", ".", "client", ",", "// loss of connectivity is possible at this point", "dc", ":", "ctx", ".", "dc", ",", "ctx", ":", "c", "}", ")", ";", "}" ]
updates the task context and notifies the client;
[ "updates", "the", "task", "context", "and", "notifies", "the", "client", ";" ]
a3ccf5a7fb14425c34892b869cb5502b2847180e
https://github.com/vitaly-t/pg-promise/blob/a3ccf5a7fb14425c34892b869cb5502b2847180e/lib/task.js#L232-L248
9,448
get-alex/alex
index.js
htmlParse
function htmlParse(value, config) { var allow if (Array.isArray(config)) { allow = config } else if (config) { allow = config.allow } return core( value, unified() .use(html) .use(rehype2retext, makeText(config)) .use(filter, {allow: allow}) ) }
javascript
function htmlParse(value, config) { var allow if (Array.isArray(config)) { allow = config } else if (config) { allow = config.allow } return core( value, unified() .use(html) .use(rehype2retext, makeText(config)) .use(filter, {allow: allow}) ) }
[ "function", "htmlParse", "(", "value", ",", "config", ")", "{", "var", "allow", "if", "(", "Array", ".", "isArray", "(", "config", ")", ")", "{", "allow", "=", "config", "}", "else", "if", "(", "config", ")", "{", "allow", "=", "config", ".", "allow", "}", "return", "core", "(", "value", ",", "unified", "(", ")", ".", "use", "(", "html", ")", ".", "use", "(", "rehype2retext", ",", "makeText", "(", "config", ")", ")", ".", "use", "(", "filter", ",", "{", "allow", ":", "allow", "}", ")", ")", "}" ]
Alex, for HTML.
[ "Alex", "for", "HTML", "." ]
4b9a763735b230c5a312afe9427cd87131bbc17d
https://github.com/get-alex/alex/blob/4b9a763735b230c5a312afe9427cd87131bbc17d/index.js#L63-L79
9,449
get-alex/alex
index.js
noMarkdown
function noMarkdown(value, config) { var allow if (Array.isArray(config)) { allow = config } else if (config) { allow = config.allow } return core(value, makeText(config).use(filter, {allow: allow})) }
javascript
function noMarkdown(value, config) { var allow if (Array.isArray(config)) { allow = config } else if (config) { allow = config.allow } return core(value, makeText(config).use(filter, {allow: allow})) }
[ "function", "noMarkdown", "(", "value", ",", "config", ")", "{", "var", "allow", "if", "(", "Array", ".", "isArray", "(", "config", ")", ")", "{", "allow", "=", "config", "}", "else", "if", "(", "config", ")", "{", "allow", "=", "config", ".", "allow", "}", "return", "core", "(", "value", ",", "makeText", "(", "config", ")", ".", "use", "(", "filter", ",", "{", "allow", ":", "allow", "}", ")", ")", "}" ]
Alex, without the markdown.
[ "Alex", "without", "the", "markdown", "." ]
4b9a763735b230c5a312afe9427cd87131bbc17d
https://github.com/get-alex/alex/blob/4b9a763735b230c5a312afe9427cd87131bbc17d/index.js#L82-L92
9,450
vuejs/vueify
lib/compilers/sass.js
function (err, res) { if (err) { cb(err) } else { res.stats.includedFiles.forEach(function (file) { compiler.emit('dependency', file) }) cb(null, res.css.toString()) } }
javascript
function (err, res) { if (err) { cb(err) } else { res.stats.includedFiles.forEach(function (file) { compiler.emit('dependency', file) }) cb(null, res.css.toString()) } }
[ "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", "}", "else", "{", "res", ".", "stats", ".", "includedFiles", ".", "forEach", "(", "function", "(", "file", ")", "{", "compiler", ".", "emit", "(", "'dependency'", ",", "file", ")", "}", ")", "cb", "(", "null", ",", "res", ".", "css", ".", "toString", "(", ")", ")", "}", "}" ]
callback for node-sass > 3.0.0
[ "callback", "for", "node", "-", "sass", ">", "3", ".", "0", ".", "0" ]
0bcabf17b6c44cbe0e4c4ff85e3c79d22a853bd8
https://github.com/vuejs/vueify/blob/0bcabf17b6c44cbe0e4c4ff85e3c79d22a853bd8/lib/compilers/sass.js#L34-L43
9,451
csstools/cssdb
tasks/start.js
sortFeatures
function sortFeatures({ stage: a, id: aa }, { stage: b, id: bb }) { return b - a || (aa < bb ? -1 : aa > bb ? 1 : 0); }
javascript
function sortFeatures({ stage: a, id: aa }, { stage: b, id: bb }) { return b - a || (aa < bb ? -1 : aa > bb ? 1 : 0); }
[ "function", "sortFeatures", "(", "{", "stage", ":", "a", ",", "id", ":", "aa", "}", ",", "{", "stage", ":", "b", ",", "id", ":", "bb", "}", ")", "{", "return", "b", "-", "a", "||", "(", "aa", "<", "bb", "?", "-", "1", ":", "aa", ">", "bb", "?", "1", ":", "0", ")", ";", "}" ]
sort features by stage or title
[ "sort", "features", "by", "stage", "or", "title" ]
1f69e619ee7fcc4aaf6c879593d120ecc96c2164
https://github.com/csstools/cssdb/blob/1f69e619ee7fcc4aaf6c879593d120ecc96c2164/tasks/start.js#L97-L99
9,452
csstools/cssdb
tasks/start.js
formatFeature
function formatFeature(feature) { return Object.assign({}, feature, { // format title using marked inline lexer title: marked.inlineLexer(feature.title, [], {}), // format description using marked inline lexer description: marked.inlineLexer(feature.description, [], {}), // format example as syntax-highlighted html example: postcss().process(feature.example, { stringifier: postcssToHTML }).css, caniuse: 'caniuse-compat' in feature ? { stats: feature['caniuse-compat'] } : feature.caniuse in caniuse.features ? trimCaniuseFeatures(caniuse.feature(caniuse.features[feature.caniuse])) : false, caniuseURL: feature.caniuse }); }
javascript
function formatFeature(feature) { return Object.assign({}, feature, { // format title using marked inline lexer title: marked.inlineLexer(feature.title, [], {}), // format description using marked inline lexer description: marked.inlineLexer(feature.description, [], {}), // format example as syntax-highlighted html example: postcss().process(feature.example, { stringifier: postcssToHTML }).css, caniuse: 'caniuse-compat' in feature ? { stats: feature['caniuse-compat'] } : feature.caniuse in caniuse.features ? trimCaniuseFeatures(caniuse.feature(caniuse.features[feature.caniuse])) : false, caniuseURL: feature.caniuse }); }
[ "function", "formatFeature", "(", "feature", ")", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "feature", ",", "{", "// format title using marked inline lexer", "title", ":", "marked", ".", "inlineLexer", "(", "feature", ".", "title", ",", "[", "]", ",", "{", "}", ")", ",", "// format description using marked inline lexer", "description", ":", "marked", ".", "inlineLexer", "(", "feature", ".", "description", ",", "[", "]", ",", "{", "}", ")", ",", "// format example as syntax-highlighted html", "example", ":", "postcss", "(", ")", ".", "process", "(", "feature", ".", "example", ",", "{", "stringifier", ":", "postcssToHTML", "}", ")", ".", "css", ",", "caniuse", ":", "'caniuse-compat'", "in", "feature", "?", "{", "stats", ":", "feature", "[", "'caniuse-compat'", "]", "}", ":", "feature", ".", "caniuse", "in", "caniuse", ".", "features", "?", "trimCaniuseFeatures", "(", "caniuse", ".", "feature", "(", "caniuse", ".", "features", "[", "feature", ".", "caniuse", "]", ")", ")", ":", "false", ",", "caniuseURL", ":", "feature", ".", "caniuse", "}", ")", ";", "}" ]
format feature for HTML output
[ "format", "feature", "for", "HTML", "output" ]
1f69e619ee7fcc4aaf6c879593d120ecc96c2164
https://github.com/csstools/cssdb/blob/1f69e619ee7fcc4aaf6c879593d120ecc96c2164/tasks/start.js#L107-L124
9,453
csstools/cssdb
tasks/start.js
postcssToHTML
function postcssToHTML(root, builder) { function toString(node) { if ('atrule' === node.type) { return atruleToString(node); } if ('rule' === node.type) { return ruleToString(node); } else if ('decl' === node.type) { return declToString(node); } else if ('comment' === node.type) { return commentToString(node); } else { return node.nodes ? node.nodes.map(childNodes => toString(childNodes)).join('') : ''; } } function replaceVars(string) { return string .replace(/:?--[\w-]+/g, '<span class=css-var>$&</span>') } function replaceVarsAndFns(string) { return replaceVars(string) .replace(/(:?[\w-]+)\(/g, '<span class=css-function>$1</span>(') .replace(/"[^"]+"/g, '<span class=css-string>$&</span>') } function atruleToString(atrule) { return `${atrule.raws.before||''}<span class=css-atrule><span class=css-atrule-name>@${atrule.name}</span>${atrule.raws.afterName||''}<span class=css-atrule-params>${replaceVarsAndFns(atrule.params)}</span>${atrule.raws.between||''}${atrule.nodes?`<span class=css-block>{${atrule.nodes.map(node => toString(node)).join('')}${atrule.raws.after||''}}</span>`:';'}</span>`; } function ruleToString(rule) { return `${rule.raws.before||''}<span class=css-rule><span class=css-selector>${replaceVars(rule.selector)}</span>${rule.raws.between||''}<span class=css-block>{${rule.nodes.map(node => toString(node)).join('')}${rule.raws.after||''}}</span></span>`; } function declToString(decl) { return `${decl.raws.before || ''}<span class=css-declaration><span class=css-property>${decl.prop}</span>${decl.raws.between || ':'}<span class=css-value>${replaceVarsAndFns(decl.value)}</span>;</span>`; } function commentToString(comment) { return `${comment.raws.before}<span class=css-comment>/*${comment.raws.left}${comment.text}${comment.raws.right}*/</span>`; } builder( toString(root) ); }
javascript
function postcssToHTML(root, builder) { function toString(node) { if ('atrule' === node.type) { return atruleToString(node); } if ('rule' === node.type) { return ruleToString(node); } else if ('decl' === node.type) { return declToString(node); } else if ('comment' === node.type) { return commentToString(node); } else { return node.nodes ? node.nodes.map(childNodes => toString(childNodes)).join('') : ''; } } function replaceVars(string) { return string .replace(/:?--[\w-]+/g, '<span class=css-var>$&</span>') } function replaceVarsAndFns(string) { return replaceVars(string) .replace(/(:?[\w-]+)\(/g, '<span class=css-function>$1</span>(') .replace(/"[^"]+"/g, '<span class=css-string>$&</span>') } function atruleToString(atrule) { return `${atrule.raws.before||''}<span class=css-atrule><span class=css-atrule-name>@${atrule.name}</span>${atrule.raws.afterName||''}<span class=css-atrule-params>${replaceVarsAndFns(atrule.params)}</span>${atrule.raws.between||''}${atrule.nodes?`<span class=css-block>{${atrule.nodes.map(node => toString(node)).join('')}${atrule.raws.after||''}}</span>`:';'}</span>`; } function ruleToString(rule) { return `${rule.raws.before||''}<span class=css-rule><span class=css-selector>${replaceVars(rule.selector)}</span>${rule.raws.between||''}<span class=css-block>{${rule.nodes.map(node => toString(node)).join('')}${rule.raws.after||''}}</span></span>`; } function declToString(decl) { return `${decl.raws.before || ''}<span class=css-declaration><span class=css-property>${decl.prop}</span>${decl.raws.between || ':'}<span class=css-value>${replaceVarsAndFns(decl.value)}</span>;</span>`; } function commentToString(comment) { return `${comment.raws.before}<span class=css-comment>/*${comment.raws.left}${comment.text}${comment.raws.right}*/</span>`; } builder( toString(root) ); }
[ "function", "postcssToHTML", "(", "root", ",", "builder", ")", "{", "function", "toString", "(", "node", ")", "{", "if", "(", "'atrule'", "===", "node", ".", "type", ")", "{", "return", "atruleToString", "(", "node", ")", ";", "}", "if", "(", "'rule'", "===", "node", ".", "type", ")", "{", "return", "ruleToString", "(", "node", ")", ";", "}", "else", "if", "(", "'decl'", "===", "node", ".", "type", ")", "{", "return", "declToString", "(", "node", ")", ";", "}", "else", "if", "(", "'comment'", "===", "node", ".", "type", ")", "{", "return", "commentToString", "(", "node", ")", ";", "}", "else", "{", "return", "node", ".", "nodes", "?", "node", ".", "nodes", ".", "map", "(", "childNodes", "=>", "toString", "(", "childNodes", ")", ")", ".", "join", "(", "''", ")", ":", "''", ";", "}", "}", "function", "replaceVars", "(", "string", ")", "{", "return", "string", ".", "replace", "(", "/", ":?--[\\w-]+", "/", "g", ",", "'<span class=css-var>$&</span>'", ")", "}", "function", "replaceVarsAndFns", "(", "string", ")", "{", "return", "replaceVars", "(", "string", ")", ".", "replace", "(", "/", "(:?[\\w-]+)\\(", "/", "g", ",", "'<span class=css-function>$1</span>('", ")", ".", "replace", "(", "/", "\"[^\"]+\"", "/", "g", ",", "'<span class=css-string>$&</span>'", ")", "}", "function", "atruleToString", "(", "atrule", ")", "{", "return", "`", "${", "atrule", ".", "raws", ".", "before", "||", "''", "}", "${", "atrule", ".", "name", "}", "${", "atrule", ".", "raws", ".", "afterName", "||", "''", "}", "${", "replaceVarsAndFns", "(", "atrule", ".", "params", ")", "}", "${", "atrule", ".", "raws", ".", "between", "||", "''", "}", "${", "atrule", ".", "nodes", "?", "`", "${", "atrule", ".", "nodes", ".", "map", "(", "node", "=>", "toString", "(", "node", ")", ")", ".", "join", "(", "''", ")", "}", "${", "atrule", ".", "raws", ".", "after", "||", "''", "}", "`", ":", "';'", "}", "`", ";", "}", "function", "ruleToString", "(", "rule", ")", "{", "return", "`", "${", "rule", ".", "raws", ".", "before", "||", "''", "}", "${", "replaceVars", "(", "rule", ".", "selector", ")", "}", "${", "rule", ".", "raws", ".", "between", "||", "''", "}", "${", "rule", ".", "nodes", ".", "map", "(", "node", "=>", "toString", "(", "node", ")", ")", ".", "join", "(", "''", ")", "}", "${", "rule", ".", "raws", ".", "after", "||", "''", "}", "`", ";", "}", "function", "declToString", "(", "decl", ")", "{", "return", "`", "${", "decl", ".", "raws", ".", "before", "||", "''", "}", "${", "decl", ".", "prop", "}", "${", "decl", ".", "raws", ".", "between", "||", "':'", "}", "${", "replaceVarsAndFns", "(", "decl", ".", "value", ")", "}", "`", ";", "}", "function", "commentToString", "(", "comment", ")", "{", "return", "`", "${", "comment", ".", "raws", ".", "before", "}", "${", "comment", ".", "raws", ".", "left", "}", "${", "comment", ".", "text", "}", "${", "comment", ".", "raws", ".", "right", "}", "`", ";", "}", "builder", "(", "toString", "(", "root", ")", ")", ";", "}" ]
format css as syntax-highlighted HTML
[ "format", "css", "as", "syntax", "-", "highlighted", "HTML" ]
1f69e619ee7fcc4aaf6c879593d120ecc96c2164
https://github.com/csstools/cssdb/blob/1f69e619ee7fcc4aaf6c879593d120ecc96c2164/tasks/start.js#L166-L211
9,454
stacktracejs/stacktrace.js
stacktrace.js
_merge
function _merge(first, second) { var target = {}; [first, second].forEach(function(obj) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { target[prop] = obj[prop]; } } return target; }); return target; }
javascript
function _merge(first, second) { var target = {}; [first, second].forEach(function(obj) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { target[prop] = obj[prop]; } } return target; }); return target; }
[ "function", "_merge", "(", "first", ",", "second", ")", "{", "var", "target", "=", "{", "}", ";", "[", "first", ",", "second", "]", ".", "forEach", "(", "function", "(", "obj", ")", "{", "for", "(", "var", "prop", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "target", "[", "prop", "]", "=", "obj", "[", "prop", "]", ";", "}", "}", "return", "target", ";", "}", ")", ";", "return", "target", ";", "}" ]
Merge 2 given Objects. If a conflict occurs the second object wins. Does not do deep merges. @param {Object} first base object @param {Object} second overrides @returns {Object} merged first and second @private
[ "Merge", "2", "given", "Objects", ".", "If", "a", "conflict", "occurs", "the", "second", "object", "wins", ".", "Does", "not", "do", "deep", "merges", "." ]
89214a1866da9eb9fb25054d64a65dea06e302dc
https://github.com/stacktracejs/stacktrace.js/blob/89214a1866da9eb9fb25054d64a65dea06e302dc/stacktrace.js#L43-L56
9,455
stacktracejs/stacktrace.js
stacktrace.js
StackTrace$$get
function StackTrace$$get(opts) { var err = _generateError(); return _isShapedLikeParsableError(err) ? this.fromError(err, opts) : this.generateArtificially(opts); }
javascript
function StackTrace$$get(opts) { var err = _generateError(); return _isShapedLikeParsableError(err) ? this.fromError(err, opts) : this.generateArtificially(opts); }
[ "function", "StackTrace$$get", "(", "opts", ")", "{", "var", "err", "=", "_generateError", "(", ")", ";", "return", "_isShapedLikeParsableError", "(", "err", ")", "?", "this", ".", "fromError", "(", "err", ",", "opts", ")", ":", "this", ".", "generateArtificially", "(", "opts", ")", ";", "}" ]
Get a backtrace from invocation point. @param {Object} opts @returns {Array} of StackFrame
[ "Get", "a", "backtrace", "from", "invocation", "point", "." ]
89214a1866da9eb9fb25054d64a65dea06e302dc
https://github.com/stacktracejs/stacktrace.js/blob/89214a1866da9eb9fb25054d64a65dea06e302dc/stacktrace.js#L76-L79
9,456
stacktracejs/stacktrace.js
stacktrace.js
StackTrace$$fromError
function StackTrace$$fromError(error, opts) { opts = _merge(_options, opts); var gps = new StackTraceGPS(opts); return new Promise(function(resolve) { var stackframes = _filtered(ErrorStackParser.parse(error), opts.filter); resolve(Promise.all(stackframes.map(function(sf) { return new Promise(function(resolve) { function resolveOriginal() { resolve(sf); } gps.pinpoint(sf).then(resolve, resolveOriginal)['catch'](resolveOriginal); }); }))); }.bind(this)); }
javascript
function StackTrace$$fromError(error, opts) { opts = _merge(_options, opts); var gps = new StackTraceGPS(opts); return new Promise(function(resolve) { var stackframes = _filtered(ErrorStackParser.parse(error), opts.filter); resolve(Promise.all(stackframes.map(function(sf) { return new Promise(function(resolve) { function resolveOriginal() { resolve(sf); } gps.pinpoint(sf).then(resolve, resolveOriginal)['catch'](resolveOriginal); }); }))); }.bind(this)); }
[ "function", "StackTrace$$fromError", "(", "error", ",", "opts", ")", "{", "opts", "=", "_merge", "(", "_options", ",", "opts", ")", ";", "var", "gps", "=", "new", "StackTraceGPS", "(", "opts", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "var", "stackframes", "=", "_filtered", "(", "ErrorStackParser", ".", "parse", "(", "error", ")", ",", "opts", ".", "filter", ")", ";", "resolve", "(", "Promise", ".", "all", "(", "stackframes", ".", "map", "(", "function", "(", "sf", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "function", "resolveOriginal", "(", ")", "{", "resolve", "(", "sf", ")", ";", "}", "gps", ".", "pinpoint", "(", "sf", ")", ".", "then", "(", "resolve", ",", "resolveOriginal", ")", "[", "'catch'", "]", "(", "resolveOriginal", ")", ";", "}", ")", ";", "}", ")", ")", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Given an error object, parse it. @param {Error} error object @param {Object} opts @returns {Promise} for Array[StackFrame}
[ "Given", "an", "error", "object", "parse", "it", "." ]
89214a1866da9eb9fb25054d64a65dea06e302dc
https://github.com/stacktracejs/stacktrace.js/blob/89214a1866da9eb9fb25054d64a65dea06e302dc/stacktrace.js#L102-L117
9,457
stacktracejs/stacktrace.js
stacktrace.js
StackTrace$$generateArtificially
function StackTrace$$generateArtificially(opts) { opts = _merge(_options, opts); var stackFrames = StackGenerator.backtrace(opts); if (typeof opts.filter === 'function') { stackFrames = stackFrames.filter(opts.filter); } return Promise.resolve(stackFrames); }
javascript
function StackTrace$$generateArtificially(opts) { opts = _merge(_options, opts); var stackFrames = StackGenerator.backtrace(opts); if (typeof opts.filter === 'function') { stackFrames = stackFrames.filter(opts.filter); } return Promise.resolve(stackFrames); }
[ "function", "StackTrace$$generateArtificially", "(", "opts", ")", "{", "opts", "=", "_merge", "(", "_options", ",", "opts", ")", ";", "var", "stackFrames", "=", "StackGenerator", ".", "backtrace", "(", "opts", ")", ";", "if", "(", "typeof", "opts", ".", "filter", "===", "'function'", ")", "{", "stackFrames", "=", "stackFrames", ".", "filter", "(", "opts", ".", "filter", ")", ";", "}", "return", "Promise", ".", "resolve", "(", "stackFrames", ")", ";", "}" ]
Use StackGenerator to generate a backtrace. @param {Object} opts @returns {Promise} of Array[StackFrame]
[ "Use", "StackGenerator", "to", "generate", "a", "backtrace", "." ]
89214a1866da9eb9fb25054d64a65dea06e302dc
https://github.com/stacktracejs/stacktrace.js/blob/89214a1866da9eb9fb25054d64a65dea06e302dc/stacktrace.js#L125-L132
9,458
stacktracejs/stacktrace.js
stacktrace.js
StackTrace$$instrument
function StackTrace$$instrument(fn, callback, errback, thisArg) { if (typeof fn !== 'function') { throw new Error('Cannot instrument non-function object'); } else if (typeof fn.__stacktraceOriginalFn === 'function') { // Already instrumented, return given Function return fn; } var instrumented = function StackTrace$$instrumented() { try { this.get().then(callback, errback)['catch'](errback); return fn.apply(thisArg || this, arguments); } catch (e) { if (_isShapedLikeParsableError(e)) { this.fromError(e).then(callback, errback)['catch'](errback); } throw e; } }.bind(this); instrumented.__stacktraceOriginalFn = fn; return instrumented; }
javascript
function StackTrace$$instrument(fn, callback, errback, thisArg) { if (typeof fn !== 'function') { throw new Error('Cannot instrument non-function object'); } else if (typeof fn.__stacktraceOriginalFn === 'function') { // Already instrumented, return given Function return fn; } var instrumented = function StackTrace$$instrumented() { try { this.get().then(callback, errback)['catch'](errback); return fn.apply(thisArg || this, arguments); } catch (e) { if (_isShapedLikeParsableError(e)) { this.fromError(e).then(callback, errback)['catch'](errback); } throw e; } }.bind(this); instrumented.__stacktraceOriginalFn = fn; return instrumented; }
[ "function", "StackTrace$$instrument", "(", "fn", ",", "callback", ",", "errback", ",", "thisArg", ")", "{", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Cannot instrument non-function object'", ")", ";", "}", "else", "if", "(", "typeof", "fn", ".", "__stacktraceOriginalFn", "===", "'function'", ")", "{", "// Already instrumented, return given Function", "return", "fn", ";", "}", "var", "instrumented", "=", "function", "StackTrace$$instrumented", "(", ")", "{", "try", "{", "this", ".", "get", "(", ")", ".", "then", "(", "callback", ",", "errback", ")", "[", "'catch'", "]", "(", "errback", ")", ";", "return", "fn", ".", "apply", "(", "thisArg", "||", "this", ",", "arguments", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "_isShapedLikeParsableError", "(", "e", ")", ")", "{", "this", ".", "fromError", "(", "e", ")", ".", "then", "(", "callback", ",", "errback", ")", "[", "'catch'", "]", "(", "errback", ")", ";", "}", "throw", "e", ";", "}", "}", ".", "bind", "(", "this", ")", ";", "instrumented", ".", "__stacktraceOriginalFn", "=", "fn", ";", "return", "instrumented", ";", "}" ]
Given a function, wrap it such that invocations trigger a callback that is called with a stack trace. @param {Function} fn to be instrumented @param {Function} callback function to call with a stack trace on invocation @param {Function} errback optional function to call with error if unable to get stack trace. @param {Object} thisArg optional context object (e.g. window)
[ "Given", "a", "function", "wrap", "it", "such", "that", "invocations", "trigger", "a", "callback", "that", "is", "called", "with", "a", "stack", "trace", "." ]
89214a1866da9eb9fb25054d64a65dea06e302dc
https://github.com/stacktracejs/stacktrace.js/blob/89214a1866da9eb9fb25054d64a65dea06e302dc/stacktrace.js#L143-L165
9,459
stacktracejs/stacktrace.js
stacktrace.js
StackTrace$$report
function StackTrace$$report(stackframes, url, errorMsg, requestOptions) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.onerror = reject; req.onreadystatechange = function onreadystatechange() { if (req.readyState === 4) { if (req.status >= 200 && req.status < 400) { resolve(req.responseText); } else { reject(new Error('POST to ' + url + ' failed with status: ' + req.status)); } } }; req.open('post', url); // Set request headers req.setRequestHeader('Content-Type', 'application/json'); if (requestOptions && typeof requestOptions.headers === 'object') { var headers = requestOptions.headers; for (var header in headers) { if (headers.hasOwnProperty(header)) { req.setRequestHeader(header, headers[header]); } } } var reportPayload = {stack: stackframes}; if (errorMsg !== undefined && errorMsg !== null) { reportPayload.message = errorMsg; } req.send(JSON.stringify(reportPayload)); }); }
javascript
function StackTrace$$report(stackframes, url, errorMsg, requestOptions) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.onerror = reject; req.onreadystatechange = function onreadystatechange() { if (req.readyState === 4) { if (req.status >= 200 && req.status < 400) { resolve(req.responseText); } else { reject(new Error('POST to ' + url + ' failed with status: ' + req.status)); } } }; req.open('post', url); // Set request headers req.setRequestHeader('Content-Type', 'application/json'); if (requestOptions && typeof requestOptions.headers === 'object') { var headers = requestOptions.headers; for (var header in headers) { if (headers.hasOwnProperty(header)) { req.setRequestHeader(header, headers[header]); } } } var reportPayload = {stack: stackframes}; if (errorMsg !== undefined && errorMsg !== null) { reportPayload.message = errorMsg; } req.send(JSON.stringify(reportPayload)); }); }
[ "function", "StackTrace$$report", "(", "stackframes", ",", "url", ",", "errorMsg", ",", "requestOptions", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "req", "=", "new", "XMLHttpRequest", "(", ")", ";", "req", ".", "onerror", "=", "reject", ";", "req", ".", "onreadystatechange", "=", "function", "onreadystatechange", "(", ")", "{", "if", "(", "req", ".", "readyState", "===", "4", ")", "{", "if", "(", "req", ".", "status", ">=", "200", "&&", "req", ".", "status", "<", "400", ")", "{", "resolve", "(", "req", ".", "responseText", ")", ";", "}", "else", "{", "reject", "(", "new", "Error", "(", "'POST to '", "+", "url", "+", "' failed with status: '", "+", "req", ".", "status", ")", ")", ";", "}", "}", "}", ";", "req", ".", "open", "(", "'post'", ",", "url", ")", ";", "// Set request headers", "req", ".", "setRequestHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "if", "(", "requestOptions", "&&", "typeof", "requestOptions", ".", "headers", "===", "'object'", ")", "{", "var", "headers", "=", "requestOptions", ".", "headers", ";", "for", "(", "var", "header", "in", "headers", ")", "{", "if", "(", "headers", ".", "hasOwnProperty", "(", "header", ")", ")", "{", "req", ".", "setRequestHeader", "(", "header", ",", "headers", "[", "header", "]", ")", ";", "}", "}", "}", "var", "reportPayload", "=", "{", "stack", ":", "stackframes", "}", ";", "if", "(", "errorMsg", "!==", "undefined", "&&", "errorMsg", "!==", "null", ")", "{", "reportPayload", ".", "message", "=", "errorMsg", ";", "}", "req", ".", "send", "(", "JSON", ".", "stringify", "(", "reportPayload", ")", ")", ";", "}", ")", ";", "}" ]
Given an error message and Array of StackFrames, serialize and POST to given URL. @param {Array} stackframes @param {String} url @param {String} errorMsg @param {Object} requestOptions
[ "Given", "an", "error", "message", "and", "Array", "of", "StackFrames", "serialize", "and", "POST", "to", "given", "URL", "." ]
89214a1866da9eb9fb25054d64a65dea06e302dc
https://github.com/stacktracejs/stacktrace.js/blob/89214a1866da9eb9fb25054d64a65dea06e302dc/stacktrace.js#L192-L225
9,460
igvteam/igv.js
js/canvas2svg.js
format
function format(str, args) { var keys = Object.keys(args), i; for (i=0; i<keys.length; i++) { str = str.replace(new RegExp("\\{" + keys[i] + "\\}", "gi"), args[keys[i]]); } return str; }
javascript
function format(str, args) { var keys = Object.keys(args), i; for (i=0; i<keys.length; i++) { str = str.replace(new RegExp("\\{" + keys[i] + "\\}", "gi"), args[keys[i]]); } return str; }
[ "function", "format", "(", "str", ",", "args", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "args", ")", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "str", "=", "str", ".", "replace", "(", "new", "RegExp", "(", "\"\\\\{\"", "+", "keys", "[", "i", "]", "+", "\"\\\\}\"", ",", "\"gi\"", ")", ",", "args", "[", "keys", "[", "i", "]", "]", ")", ";", "}", "return", "str", ";", "}" ]
helper function to format a string
[ "helper", "function", "to", "format", "a", "string" ]
b9473ee0b8565ee4e5eb98f73f8d6161dda2acb6
https://github.com/igvteam/igv.js/blob/b9473ee0b8565ee4e5eb98f73f8d6161dda2acb6/js/canvas2svg.js#L22-L28
9,461
igvteam/igv.js
js/canvas2svg.js
randomString
function randomString(holder) { var chars, randomstring, i; if (!holder) { throw new Error("cannot create a random attribute name for an undefined object"); } chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; randomstring = ""; do { randomstring = ""; for (i = 0; i < 12; i++) { randomstring += chars[Math.floor(Math.random() * chars.length)]; } } while (holder[randomstring]); return randomstring; }
javascript
function randomString(holder) { var chars, randomstring, i; if (!holder) { throw new Error("cannot create a random attribute name for an undefined object"); } chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; randomstring = ""; do { randomstring = ""; for (i = 0; i < 12; i++) { randomstring += chars[Math.floor(Math.random() * chars.length)]; } } while (holder[randomstring]); return randomstring; }
[ "function", "randomString", "(", "holder", ")", "{", "var", "chars", ",", "randomstring", ",", "i", ";", "if", "(", "!", "holder", ")", "{", "throw", "new", "Error", "(", "\"cannot create a random attribute name for an undefined object\"", ")", ";", "}", "chars", "=", "\"ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz\"", ";", "randomstring", "=", "\"\"", ";", "do", "{", "randomstring", "=", "\"\"", ";", "for", "(", "i", "=", "0", ";", "i", "<", "12", ";", "i", "++", ")", "{", "randomstring", "+=", "chars", "[", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "chars", ".", "length", ")", "]", ";", "}", "}", "while", "(", "holder", "[", "randomstring", "]", ")", ";", "return", "randomstring", ";", "}" ]
helper function that generates a random string
[ "helper", "function", "that", "generates", "a", "random", "string" ]
b9473ee0b8565ee4e5eb98f73f8d6161dda2acb6
https://github.com/igvteam/igv.js/blob/b9473ee0b8565ee4e5eb98f73f8d6161dda2acb6/js/canvas2svg.js#L31-L45
9,462
igvteam/igv.js
js/canvas2svg.js
createNamedToNumberedLookup
function createNamedToNumberedLookup(items, radix) { var i, entity, lookup = {}, base10, base16; items = items.split(','); radix = radix || 10; // Map from named to numbered entities. for (i = 0; i < items.length; i += 2) { entity = '&' + items[i + 1] + ';'; base10 = parseInt(items[i], radix); lookup[entity] = '&#'+base10+';'; } //FF and IE need to create a regex from hex values ie &nbsp; == \xa0 lookup["\\xa0"] = '&#160;'; return lookup; }
javascript
function createNamedToNumberedLookup(items, radix) { var i, entity, lookup = {}, base10, base16; items = items.split(','); radix = radix || 10; // Map from named to numbered entities. for (i = 0; i < items.length; i += 2) { entity = '&' + items[i + 1] + ';'; base10 = parseInt(items[i], radix); lookup[entity] = '&#'+base10+';'; } //FF and IE need to create a regex from hex values ie &nbsp; == \xa0 lookup["\\xa0"] = '&#160;'; return lookup; }
[ "function", "createNamedToNumberedLookup", "(", "items", ",", "radix", ")", "{", "var", "i", ",", "entity", ",", "lookup", "=", "{", "}", ",", "base10", ",", "base16", ";", "items", "=", "items", ".", "split", "(", "','", ")", ";", "radix", "=", "radix", "||", "10", ";", "// Map from named to numbered entities.", "for", "(", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "+=", "2", ")", "{", "entity", "=", "'&'", "+", "items", "[", "i", "+", "1", "]", "+", "';'", ";", "base10", "=", "parseInt", "(", "items", "[", "i", "]", ",", "radix", ")", ";", "lookup", "[", "entity", "]", "=", "'&#'", "+", "base10", "+", "';'", ";", "}", "//FF and IE need to create a regex from hex values ie &nbsp; == \\xa0", "lookup", "[", "\"\\\\xa0\"", "]", "=", "'&#160;'", ";", "return", "lookup", ";", "}" ]
helper function to map named to numbered entities
[ "helper", "function", "to", "map", "named", "to", "numbered", "entities" ]
b9473ee0b8565ee4e5eb98f73f8d6161dda2acb6
https://github.com/igvteam/igv.js/blob/b9473ee0b8565ee4e5eb98f73f8d6161dda2acb6/js/canvas2svg.js#L48-L61
9,463
igvteam/igv.js
js/canvas2svg.js
function (vector) { var len = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]); return [vector[0] / len, vector[1] / len]; }
javascript
function (vector) { var len = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]); return [vector[0] / len, vector[1] / len]; }
[ "function", "(", "vector", ")", "{", "var", "len", "=", "Math", ".", "sqrt", "(", "vector", "[", "0", "]", "*", "vector", "[", "0", "]", "+", "vector", "[", "1", "]", "*", "vector", "[", "1", "]", ")", ";", "return", "[", "vector", "[", "0", "]", "/", "len", ",", "vector", "[", "1", "]", "/", "len", "]", ";", "}" ]
Return a new normalized vector of given vector
[ "Return", "a", "new", "normalized", "vector", "of", "given", "vector" ]
b9473ee0b8565ee4e5eb98f73f8d6161dda2acb6
https://github.com/igvteam/igv.js/blob/b9473ee0b8565ee4e5eb98f73f8d6161dda2acb6/js/canvas2svg.js#L709-L712
9,464
skaterdav85/validatorjs
src/validator.js
function (passes, fails) { var _this = this; passes = passes || function () {}; fails = fails || function () {}; var failsOne = function (rule, message) { _this._addFailure(rule, message); }; var resolvedAll = function (allPassed) { if (allPassed) { passes(); } else { fails(); } }; var asyncResolvers = new AsyncResolvers(failsOne, resolvedAll); var validateRule = function (inputValue, ruleOptions, attribute, rule) { return function () { var resolverIndex = asyncResolvers.add(rule); rule.validate(inputValue, ruleOptions.value, attribute, function () { asyncResolvers.resolve(resolverIndex); }); }; }; for (var attribute in this.rules) { var attributeRules = this.rules[attribute]; var inputValue = this._objectPath(this.input, attribute); if (this._hasRule(attribute, ['sometimes']) && !this._suppliedWithData(attribute)) { continue; } for (var i = 0, len = attributeRules.length, rule, ruleOptions; i < len; i++) { ruleOptions = attributeRules[i]; rule = this.getRule(ruleOptions.name); if (!this._isValidatable(rule, inputValue)) { continue; } validateRule(inputValue, ruleOptions, attribute, rule)(); } } asyncResolvers.enableFiring(); asyncResolvers.fire(); }
javascript
function (passes, fails) { var _this = this; passes = passes || function () {}; fails = fails || function () {}; var failsOne = function (rule, message) { _this._addFailure(rule, message); }; var resolvedAll = function (allPassed) { if (allPassed) { passes(); } else { fails(); } }; var asyncResolvers = new AsyncResolvers(failsOne, resolvedAll); var validateRule = function (inputValue, ruleOptions, attribute, rule) { return function () { var resolverIndex = asyncResolvers.add(rule); rule.validate(inputValue, ruleOptions.value, attribute, function () { asyncResolvers.resolve(resolverIndex); }); }; }; for (var attribute in this.rules) { var attributeRules = this.rules[attribute]; var inputValue = this._objectPath(this.input, attribute); if (this._hasRule(attribute, ['sometimes']) && !this._suppliedWithData(attribute)) { continue; } for (var i = 0, len = attributeRules.length, rule, ruleOptions; i < len; i++) { ruleOptions = attributeRules[i]; rule = this.getRule(ruleOptions.name); if (!this._isValidatable(rule, inputValue)) { continue; } validateRule(inputValue, ruleOptions, attribute, rule)(); } } asyncResolvers.enableFiring(); asyncResolvers.fire(); }
[ "function", "(", "passes", ",", "fails", ")", "{", "var", "_this", "=", "this", ";", "passes", "=", "passes", "||", "function", "(", ")", "{", "}", ";", "fails", "=", "fails", "||", "function", "(", ")", "{", "}", ";", "var", "failsOne", "=", "function", "(", "rule", ",", "message", ")", "{", "_this", ".", "_addFailure", "(", "rule", ",", "message", ")", ";", "}", ";", "var", "resolvedAll", "=", "function", "(", "allPassed", ")", "{", "if", "(", "allPassed", ")", "{", "passes", "(", ")", ";", "}", "else", "{", "fails", "(", ")", ";", "}", "}", ";", "var", "asyncResolvers", "=", "new", "AsyncResolvers", "(", "failsOne", ",", "resolvedAll", ")", ";", "var", "validateRule", "=", "function", "(", "inputValue", ",", "ruleOptions", ",", "attribute", ",", "rule", ")", "{", "return", "function", "(", ")", "{", "var", "resolverIndex", "=", "asyncResolvers", ".", "add", "(", "rule", ")", ";", "rule", ".", "validate", "(", "inputValue", ",", "ruleOptions", ".", "value", ",", "attribute", ",", "function", "(", ")", "{", "asyncResolvers", ".", "resolve", "(", "resolverIndex", ")", ";", "}", ")", ";", "}", ";", "}", ";", "for", "(", "var", "attribute", "in", "this", ".", "rules", ")", "{", "var", "attributeRules", "=", "this", ".", "rules", "[", "attribute", "]", ";", "var", "inputValue", "=", "this", ".", "_objectPath", "(", "this", ".", "input", ",", "attribute", ")", ";", "if", "(", "this", ".", "_hasRule", "(", "attribute", ",", "[", "'sometimes'", "]", ")", "&&", "!", "this", ".", "_suppliedWithData", "(", "attribute", ")", ")", "{", "continue", ";", "}", "for", "(", "var", "i", "=", "0", ",", "len", "=", "attributeRules", ".", "length", ",", "rule", ",", "ruleOptions", ";", "i", "<", "len", ";", "i", "++", ")", "{", "ruleOptions", "=", "attributeRules", "[", "i", "]", ";", "rule", "=", "this", ".", "getRule", "(", "ruleOptions", ".", "name", ")", ";", "if", "(", "!", "this", ".", "_isValidatable", "(", "rule", ",", "inputValue", ")", ")", "{", "continue", ";", "}", "validateRule", "(", "inputValue", ",", "ruleOptions", ",", "attribute", ",", "rule", ")", "(", ")", ";", "}", "}", "asyncResolvers", ".", "enableFiring", "(", ")", ";", "asyncResolvers", ".", "fire", "(", ")", ";", "}" ]
Run async validator @param {function} passes @param {function} fails @return {void}
[ "Run", "async", "validator" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/validator.js#L92-L143
9,465
skaterdav85/validatorjs
src/validator.js
function (rule) { var msg = this.messages.render(rule); this.errors.add(rule.attribute, msg); this.errorCount++; }
javascript
function (rule) { var msg = this.messages.render(rule); this.errors.add(rule.attribute, msg); this.errorCount++; }
[ "function", "(", "rule", ")", "{", "var", "msg", "=", "this", ".", "messages", ".", "render", "(", "rule", ")", ";", "this", ".", "errors", ".", "add", "(", "rule", ".", "attribute", ",", "msg", ")", ";", "this", ".", "errorCount", "++", ";", "}" ]
Add failure and error message for given rule @param {Rule} rule
[ "Add", "failure", "and", "error", "message", "for", "given", "rule" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/validator.js#L150-L154
9,466
skaterdav85/validatorjs
src/validator.js
function (obj, path) { if (Object.prototype.hasOwnProperty.call(obj, path)) { return obj[path]; } var keys = path.replace(/\[(\w+)\]/g, ".$1").replace(/^\./, "").split("."); var copy = {}; for (var attr in obj) { if (Object.prototype.hasOwnProperty.call(obj, attr)) { copy[attr] = obj[attr]; } } for (var i = 0, l = keys.length; i < l; i++) { if (Object.hasOwnProperty.call(copy, keys[i])) { copy = copy[keys[i]]; } else { return; } } return copy; }
javascript
function (obj, path) { if (Object.prototype.hasOwnProperty.call(obj, path)) { return obj[path]; } var keys = path.replace(/\[(\w+)\]/g, ".$1").replace(/^\./, "").split("."); var copy = {}; for (var attr in obj) { if (Object.prototype.hasOwnProperty.call(obj, attr)) { copy[attr] = obj[attr]; } } for (var i = 0, l = keys.length; i < l; i++) { if (Object.hasOwnProperty.call(copy, keys[i])) { copy = copy[keys[i]]; } else { return; } } return copy; }
[ "function", "(", "obj", ",", "path", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "obj", ",", "path", ")", ")", "{", "return", "obj", "[", "path", "]", ";", "}", "var", "keys", "=", "path", ".", "replace", "(", "/", "\\[(\\w+)\\]", "/", "g", ",", "\".$1\"", ")", ".", "replace", "(", "/", "^\\.", "/", ",", "\"\"", ")", ".", "split", "(", "\".\"", ")", ";", "var", "copy", "=", "{", "}", ";", "for", "(", "var", "attr", "in", "obj", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "obj", ",", "attr", ")", ")", "{", "copy", "[", "attr", "]", "=", "obj", "[", "attr", "]", ";", "}", "}", "for", "(", "var", "i", "=", "0", ",", "l", "=", "keys", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "Object", ".", "hasOwnProperty", ".", "call", "(", "copy", ",", "keys", "[", "i", "]", ")", ")", "{", "copy", "=", "copy", "[", "keys", "[", "i", "]", "]", ";", "}", "else", "{", "return", ";", "}", "}", "return", "copy", ";", "}" ]
Extract value from nested object using string path with dot notation @param {object} object to search in @param {string} path inside object @return {any|void} value under the path
[ "Extract", "value", "from", "nested", "object", "using", "string", "path", "with", "dot", "notation" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/validator.js#L195-L216
9,467
skaterdav85/validatorjs
src/validator.js
function (rulesArray) { var rules = []; for (var i = 0, len = rulesArray.length; i < len; i++) { if (typeof rulesArray[i] === 'object') { for (var rule in rulesArray[i]) { rules.push({ name: rule, value: rulesArray[i][rule] }); } } else { rules.push(rulesArray[i]); } } return rules; }
javascript
function (rulesArray) { var rules = []; for (var i = 0, len = rulesArray.length; i < len; i++) { if (typeof rulesArray[i] === 'object') { for (var rule in rulesArray[i]) { rules.push({ name: rule, value: rulesArray[i][rule] }); } } else { rules.push(rulesArray[i]); } } return rules; }
[ "function", "(", "rulesArray", ")", "{", "var", "rules", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "rulesArray", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "typeof", "rulesArray", "[", "i", "]", "===", "'object'", ")", "{", "for", "(", "var", "rule", "in", "rulesArray", "[", "i", "]", ")", "{", "rules", ".", "push", "(", "{", "name", ":", "rule", ",", "value", ":", "rulesArray", "[", "i", "]", "[", "rule", "]", "}", ")", ";", "}", "}", "else", "{", "rules", ".", "push", "(", "rulesArray", "[", "i", "]", ")", ";", "}", "}", "return", "rules", ";", "}" ]
Prepare rules if it comes in Array. Check for objects. Need for type validation. @param {array} rulesArray @return {array}
[ "Prepare", "rules", "if", "it", "comes", "in", "Array", ".", "Check", "for", "objects", ".", "Need", "for", "type", "validation", "." ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/validator.js#L330-L347
9,468
skaterdav85/validatorjs
src/validator.js
function (attribute, findRules) { var rules = this.rules[attribute] || []; for (var i = 0, len = rules.length; i < len; i++) { if (findRules.indexOf(rules[i].name) > -1) { return true; } } return false; }
javascript
function (attribute, findRules) { var rules = this.rules[attribute] || []; for (var i = 0, len = rules.length; i < len; i++) { if (findRules.indexOf(rules[i].name) > -1) { return true; } } return false; }
[ "function", "(", "attribute", ",", "findRules", ")", "{", "var", "rules", "=", "this", ".", "rules", "[", "attribute", "]", "||", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "rules", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "findRules", ".", "indexOf", "(", "rules", "[", "i", "]", ".", "name", ")", ">", "-", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine if attribute has any of the given rules @param {string} attribute @param {array} findRules @return {boolean}
[ "Determine", "if", "attribute", "has", "any", "of", "the", "given", "rules" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/validator.js#L387-L395
9,469
skaterdav85/validatorjs
src/validator.js
function (rule, value) { if (Rules.isImplicit(rule.name)) { return true; } return this.getRule('required').validate(value); }
javascript
function (rule, value) { if (Rules.isImplicit(rule.name)) { return true; } return this.getRule('required').validate(value); }
[ "function", "(", "rule", ",", "value", ")", "{", "if", "(", "Rules", ".", "isImplicit", "(", "rule", ".", "name", ")", ")", "{", "return", "true", ";", "}", "return", "this", ".", "getRule", "(", "'required'", ")", ".", "validate", "(", "value", ")", ";", "}" ]
Determine if rule is validatable @param {Rule} rule @param {mixed} value @return {boolean}
[ "Determine", "if", "rule", "is", "validatable" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/validator.js#L414-L420
9,470
skaterdav85/validatorjs
src/validator.js
function (attribute, rulePassed) { var stopOnAttributes = this.stopOnAttributes; if (typeof stopOnAttributes === 'undefined' || stopOnAttributes === false || rulePassed === true) { return false; } if (stopOnAttributes instanceof Array) { return stopOnAttributes.indexOf(attribute) > -1; } return true; }
javascript
function (attribute, rulePassed) { var stopOnAttributes = this.stopOnAttributes; if (typeof stopOnAttributes === 'undefined' || stopOnAttributes === false || rulePassed === true) { return false; } if (stopOnAttributes instanceof Array) { return stopOnAttributes.indexOf(attribute) > -1; } return true; }
[ "function", "(", "attribute", ",", "rulePassed", ")", "{", "var", "stopOnAttributes", "=", "this", ".", "stopOnAttributes", ";", "if", "(", "typeof", "stopOnAttributes", "===", "'undefined'", "||", "stopOnAttributes", "===", "false", "||", "rulePassed", "===", "true", ")", "{", "return", "false", ";", "}", "if", "(", "stopOnAttributes", "instanceof", "Array", ")", "{", "return", "stopOnAttributes", ".", "indexOf", "(", "attribute", ")", ">", "-", "1", ";", "}", "return", "true", ";", "}" ]
Determine if we should stop validating. @param {string} attribute @param {boolean} rulePassed @return {boolean}
[ "Determine", "if", "we", "should", "stop", "validating", "." ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/validator.js#L429-L441
9,471
skaterdav85/validatorjs
src/rules.js
function(val, req, attribute) { if (val) { req = parseFloat(req); var size = this.getSize(); return size === req; } return true; }
javascript
function(val, req, attribute) { if (val) { req = parseFloat(req); var size = this.getSize(); return size === req; } return true; }
[ "function", "(", "val", ",", "req", ",", "attribute", ")", "{", "if", "(", "val", ")", "{", "req", "=", "parseFloat", "(", "req", ")", ";", "var", "size", "=", "this", ".", "getSize", "(", ")", ";", "return", "size", "===", "req", ";", "}", "return", "true", ";", "}" ]
compares the size of strings with numbers, compares the value
[ "compares", "the", "size", "of", "strings", "with", "numbers", "compares", "the", "value" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/rules.js#L121-L131
9,472
skaterdav85/validatorjs
src/rules.js
function(inputValue, ruleValue, attribute, callback) { var fn = this.isMissed() ? missedRuleValidator : this.fn; return fn.apply(this, [inputValue, ruleValue, attribute, callback]); }
javascript
function(inputValue, ruleValue, attribute, callback) { var fn = this.isMissed() ? missedRuleValidator : this.fn; return fn.apply(this, [inputValue, ruleValue, attribute, callback]); }
[ "function", "(", "inputValue", ",", "ruleValue", ",", "attribute", ",", "callback", ")", "{", "var", "fn", "=", "this", ".", "isMissed", "(", ")", "?", "missedRuleValidator", ":", "this", ".", "fn", ";", "return", "fn", ".", "apply", "(", "this", ",", "[", "inputValue", ",", "ruleValue", ",", "attribute", ",", "callback", "]", ")", ";", "}" ]
Apply validation function @param {mixed} inputValue @param {mixed} ruleValue @param {string} attribute @param {function} callback @return {boolean|undefined}
[ "Apply", "validation", "function" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/rules.js#L439-L443
9,473
skaterdav85/validatorjs
src/rules.js
function() { var value = this.inputValue; if (value instanceof Array) { return value.length; } if (typeof value === 'number') { return value; } if (this.validator._hasNumericRule(this.attribute)) { return parseFloat(value, 10); } return value.length; }
javascript
function() { var value = this.inputValue; if (value instanceof Array) { return value.length; } if (typeof value === 'number') { return value; } if (this.validator._hasNumericRule(this.attribute)) { return parseFloat(value, 10); } return value.length; }
[ "function", "(", ")", "{", "var", "value", "=", "this", ".", "inputValue", ";", "if", "(", "value", "instanceof", "Array", ")", "{", "return", "value", ".", "length", ";", "}", "if", "(", "typeof", "value", "===", "'number'", ")", "{", "return", "value", ";", "}", "if", "(", "this", ".", "validator", ".", "_hasNumericRule", "(", "this", ".", "attribute", ")", ")", "{", "return", "parseFloat", "(", "value", ",", "10", ")", ";", "}", "return", "value", ".", "length", ";", "}" ]
Get true size of value @return {integer|float}
[ "Get", "true", "size", "of", "value" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/rules.js#L487-L503
9,474
skaterdav85/validatorjs
src/rules.js
function(passes, message) { this.passes = (passes === undefined || passes === true); this._customMessage = message; this.callback(this.passes, message); }
javascript
function(passes, message) { this.passes = (passes === undefined || passes === true); this._customMessage = message; this.callback(this.passes, message); }
[ "function", "(", "passes", ",", "message", ")", "{", "this", ".", "passes", "=", "(", "passes", "===", "undefined", "||", "passes", "===", "true", ")", ";", "this", ".", "_customMessage", "=", "message", ";", "this", ".", "callback", "(", "this", ".", "passes", ",", "message", ")", ";", "}" ]
Set the async callback response @param {boolean|undefined} passes Whether validation passed @param {string|undefined} message Custom error message @return {void}
[ "Set", "the", "async", "callback", "response" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/rules.js#L526-L530
9,475
skaterdav85/validatorjs
src/rules.js
function(name, validator) { var async = this.isAsync(name); var rule = new Rule(name, rules[name], async); rule.setValidator(validator); return rule; }
javascript
function(name, validator) { var async = this.isAsync(name); var rule = new Rule(name, rules[name], async); rule.setValidator(validator); return rule; }
[ "function", "(", "name", ",", "validator", ")", "{", "var", "async", "=", "this", ".", "isAsync", "(", "name", ")", ";", "var", "rule", "=", "new", "Rule", "(", "name", ",", "rules", "[", "name", "]", ",", "async", ")", ";", "rule", ".", "setValidator", "(", "validator", ")", ";", "return", "rule", ";", "}" ]
Get rule by name @param {string} name @param {Validator} @return {Rule}
[ "Get", "rule", "by", "name" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/rules.js#L579-L584
9,476
skaterdav85/validatorjs
src/rules.js
function(name) { for (var i = 0, len = this.asyncRules.length; i < len; i++) { if (this.asyncRules[i] === name) { return true; } } return false; }
javascript
function(name) { for (var i = 0, len = this.asyncRules.length; i < len; i++) { if (this.asyncRules[i] === name) { return true; } } return false; }
[ "function", "(", "name", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "this", ".", "asyncRules", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "this", ".", "asyncRules", "[", "i", "]", "===", "name", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine if given rule is async @param {string} name @return {boolean}
[ "Determine", "if", "given", "rule", "is", "async" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/rules.js#L592-L599
9,477
skaterdav85/validatorjs
src/errors.js
function(attribute, message) { if (!this.has(attribute)) { this.errors[attribute] = []; } if (this.errors[attribute].indexOf(message) === -1) { this.errors[attribute].push(message); } }
javascript
function(attribute, message) { if (!this.has(attribute)) { this.errors[attribute] = []; } if (this.errors[attribute].indexOf(message) === -1) { this.errors[attribute].push(message); } }
[ "function", "(", "attribute", ",", "message", ")", "{", "if", "(", "!", "this", ".", "has", "(", "attribute", ")", ")", "{", "this", ".", "errors", "[", "attribute", "]", "=", "[", "]", ";", "}", "if", "(", "this", ".", "errors", "[", "attribute", "]", ".", "indexOf", "(", "message", ")", "===", "-", "1", ")", "{", "this", ".", "errors", "[", "attribute", "]", ".", "push", "(", "message", ")", ";", "}", "}" ]
Add new error message for given attribute @param {string} attribute @param {string} message @return {void}
[ "Add", "new", "error", "message", "for", "given", "attribute" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/errors.js#L15-L23
9,478
skaterdav85/validatorjs
src/async.js
function(index) { var rule = this.resolvers[index]; if (rule.passes === true) { this.passed.push(rule); } else if (rule.passes === false) { this.failed.push(rule); this.onFailedOne(rule); } this.fire(); }
javascript
function(index) { var rule = this.resolvers[index]; if (rule.passes === true) { this.passed.push(rule); } else if (rule.passes === false) { this.failed.push(rule); this.onFailedOne(rule); } this.fire(); }
[ "function", "(", "index", ")", "{", "var", "rule", "=", "this", ".", "resolvers", "[", "index", "]", ";", "if", "(", "rule", ".", "passes", "===", "true", ")", "{", "this", ".", "passed", ".", "push", "(", "rule", ")", ";", "}", "else", "if", "(", "rule", ".", "passes", "===", "false", ")", "{", "this", ".", "failed", ".", "push", "(", "rule", ")", ";", "this", ".", "onFailedOne", "(", "rule", ")", ";", "}", "this", ".", "fire", "(", ")", ";", "}" ]
Resolve given index @param {integer} index @return {void}
[ "Resolve", "given", "index" ]
7cdb58f064a77237de13072057dc35e61755a7f5
https://github.com/skaterdav85/validatorjs/blob/7cdb58f064a77237de13072057dc35e61755a7f5/src/async.js#L32-L42
9,479
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/common.js
ancestors
function ancestors(first, second) { var path = []; for (var n in first.path) { if (first.path[n] !== second.path[n]) break; path.push(first.path[n]); } return path; }
javascript
function ancestors(first, second) { var path = []; for (var n in first.path) { if (first.path[n] !== second.path[n]) break; path.push(first.path[n]); } return path; }
[ "function", "ancestors", "(", "first", ",", "second", ")", "{", "var", "path", "=", "[", "]", ";", "for", "(", "var", "n", "in", "first", ".", "path", ")", "{", "if", "(", "first", ".", "path", "[", "n", "]", "!==", "second", ".", "path", "[", "n", "]", ")", "break", ";", "path", ".", "push", "(", "first", ".", "path", "[", "n", "]", ")", ";", "}", "return", "path", ";", "}" ]
Finds the common ancestor path between two states. @param {Object} first The first state. @param {Object} second The second state. @return {Array} Returns an array of state names in descending order, not including the root.
[ "Finds", "the", "common", "ancestor", "path", "between", "two", "states", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/common.js#L36-L44
9,480
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/common.js
equalForKeys
function equalForKeys(a, b, keys) { if (!keys) { keys = []; for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility } for (var i=0; i<keys.length; i++) { var k = keys[i]; if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized } return true; }
javascript
function equalForKeys(a, b, keys) { if (!keys) { keys = []; for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility } for (var i=0; i<keys.length; i++) { var k = keys[i]; if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized } return true; }
[ "function", "equalForKeys", "(", "a", ",", "b", ",", "keys", ")", "{", "if", "(", "!", "keys", ")", "{", "keys", "=", "[", "]", ";", "for", "(", "var", "n", "in", "a", ")", "keys", ".", "push", "(", "n", ")", ";", "// Used instead of Object.keys() for IE8 compatibility", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "k", "=", "keys", "[", "i", "]", ";", "if", "(", "a", "[", "k", "]", "!=", "b", "[", "k", "]", ")", "return", "false", ";", "// Not '===', values aren't necessarily normalized", "}", "return", "true", ";", "}" ]
Performs a non-strict comparison of the subset of two objects, defined by a list of keys. @param {Object} a The first object. @param {Object} b The second object. @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified, it defaults to the list of keys in `a`. @return {Boolean} Returns `true` if the keys match, otherwise `false`.
[ "Performs", "a", "non", "-", "strict", "comparison", "of", "the", "subset", "of", "two", "objects", "defined", "by", "a", "list", "of", "keys", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/common.js#L121-L132
9,481
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/common.js
filterByKeys
function filterByKeys(keys, values) { var filtered = {}; forEach(keys, function (name) { filtered[name] = values[name]; }); return filtered; }
javascript
function filterByKeys(keys, values) { var filtered = {}; forEach(keys, function (name) { filtered[name] = values[name]; }); return filtered; }
[ "function", "filterByKeys", "(", "keys", ",", "values", ")", "{", "var", "filtered", "=", "{", "}", ";", "forEach", "(", "keys", ",", "function", "(", "name", ")", "{", "filtered", "[", "name", "]", "=", "values", "[", "name", "]", ";", "}", ")", ";", "return", "filtered", ";", "}" ]
Returns the subset of an object, based on a list of keys. @param {Array} keys @param {Object} values @return {Boolean} Returns a subset of `values`.
[ "Returns", "the", "subset", "of", "an", "object", "based", "on", "a", "list", "of", "keys", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/common.js#L141-L148
9,482
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/common.js
indexBy
function indexBy(array, propName) { var result = {}; forEach(array, function(item) { result[item[propName]] = item; }); return result; }
javascript
function indexBy(array, propName) { var result = {}; forEach(array, function(item) { result[item[propName]] = item; }); return result; }
[ "function", "indexBy", "(", "array", ",", "propName", ")", "{", "var", "result", "=", "{", "}", ";", "forEach", "(", "array", ",", "function", "(", "item", ")", "{", "result", "[", "item", "[", "propName", "]", "]", "=", "item", ";", "}", ")", ";", "return", "result", ";", "}" ]
like _.indexBy when you know that your index values will be unique, or you want last-one-in to win
[ "like", "_", ".", "indexBy", "when", "you", "know", "that", "your", "index", "values", "will", "be", "unique", "or", "you", "want", "last", "-", "one", "-", "in", "to", "win" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/common.js#L152-L158
9,483
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/common.js
pick
function pick(obj) { var copy = {}; var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); forEach(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }
javascript
function pick(obj) { var copy = {}; var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); forEach(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }
[ "function", "pick", "(", "obj", ")", "{", "var", "copy", "=", "{", "}", ";", "var", "keys", "=", "Array", ".", "prototype", ".", "concat", ".", "apply", "(", "Array", ".", "prototype", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "forEach", "(", "keys", ",", "function", "(", "key", ")", "{", "if", "(", "key", "in", "obj", ")", "copy", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", ")", ";", "return", "copy", ";", "}" ]
extracted from underscore.js Return a copy of the object only containing the whitelisted properties.
[ "extracted", "from", "underscore", ".", "js", "Return", "a", "copy", "of", "the", "object", "only", "containing", "the", "whitelisted", "properties", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/common.js#L162-L169
9,484
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/common.js
omit
function omit(obj) { var copy = {}; var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); for (var key in obj) { if (indexOf(keys, key) == -1) copy[key] = obj[key]; } return copy; }
javascript
function omit(obj) { var copy = {}; var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); for (var key in obj) { if (indexOf(keys, key) == -1) copy[key] = obj[key]; } return copy; }
[ "function", "omit", "(", "obj", ")", "{", "var", "copy", "=", "{", "}", ";", "var", "keys", "=", "Array", ".", "prototype", ".", "concat", ".", "apply", "(", "Array", ".", "prototype", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "indexOf", "(", "keys", ",", "key", ")", "==", "-", "1", ")", "copy", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", "return", "copy", ";", "}" ]
extracted from underscore.js Return a copy of the object omitting the blacklisted properties.
[ "extracted", "from", "underscore", ".", "js", "Return", "a", "copy", "of", "the", "object", "omitting", "the", "blacklisted", "properties", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/common.js#L173-L180
9,485
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/state.js
function(state) { var url = state.url, config = { params: state.params || {} }; if (isString(url)) { if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config); return (state.parent.navigable || root).url.concat(url, config); } if (!url || $urlMatcherFactory.isMatcher(url)) return url; throw new Error("Invalid url '" + url + "' in state '" + state + "'"); }
javascript
function(state) { var url = state.url, config = { params: state.params || {} }; if (isString(url)) { if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config); return (state.parent.navigable || root).url.concat(url, config); } if (!url || $urlMatcherFactory.isMatcher(url)) return url; throw new Error("Invalid url '" + url + "' in state '" + state + "'"); }
[ "function", "(", "state", ")", "{", "var", "url", "=", "state", ".", "url", ",", "config", "=", "{", "params", ":", "state", ".", "params", "||", "{", "}", "}", ";", "if", "(", "isString", "(", "url", ")", ")", "{", "if", "(", "url", ".", "charAt", "(", "0", ")", "==", "'^'", ")", "return", "$urlMatcherFactory", ".", "compile", "(", "url", ".", "substring", "(", "1", ")", ",", "config", ")", ";", "return", "(", "state", ".", "parent", ".", "navigable", "||", "root", ")", ".", "url", ".", "concat", "(", "url", ",", "config", ")", ";", "}", "if", "(", "!", "url", "||", "$urlMatcherFactory", ".", "isMatcher", "(", "url", ")", ")", "return", "url", ";", "throw", "new", "Error", "(", "\"Invalid url '\"", "+", "url", "+", "\"' in state '\"", "+", "state", "+", "\"'\"", ")", ";", "}" ]
Build a URLMatcher if necessary, either via a relative or absolute URL
[ "Build", "a", "URLMatcher", "if", "necessary", "either", "via", "a", "relative", "or", "absolute", "URL" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/state.js#L50-L60
9,486
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/state.js
function(state) { var params = state.url && state.url.params || new $$UMFP.ParamSet(); forEach(state.params || {}, function(config, id) { if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config"); }); return params; }
javascript
function(state) { var params = state.url && state.url.params || new $$UMFP.ParamSet(); forEach(state.params || {}, function(config, id) { if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config"); }); return params; }
[ "function", "(", "state", ")", "{", "var", "params", "=", "state", ".", "url", "&&", "state", ".", "url", ".", "params", "||", "new", "$$UMFP", ".", "ParamSet", "(", ")", ";", "forEach", "(", "state", ".", "params", "||", "{", "}", ",", "function", "(", "config", ",", "id", ")", "{", "if", "(", "!", "params", "[", "id", "]", ")", "params", "[", "id", "]", "=", "new", "$$UMFP", ".", "Param", "(", "id", ",", "null", ",", "config", ",", "\"config\"", ")", ";", "}", ")", ";", "return", "params", ";", "}" ]
Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
[ "Own", "parameters", "for", "this", "state", ".", "state", ".", "url", ".", "params", "is", "already", "built", "at", "this", "point", ".", "Create", "and", "add", "non", "-", "url", "params" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/state.js#L68-L74
9,487
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/state.js
function(state) { var views = {}; forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) { if (name.indexOf('@') < 0) name += '@' + state.parent.name; views[name] = view; }); return views; }
javascript
function(state) { var views = {}; forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) { if (name.indexOf('@') < 0) name += '@' + state.parent.name; views[name] = view; }); return views; }
[ "function", "(", "state", ")", "{", "var", "views", "=", "{", "}", ";", "forEach", "(", "isDefined", "(", "state", ".", "views", ")", "?", "state", ".", "views", ":", "{", "''", ":", "state", "}", ",", "function", "(", "view", ",", "name", ")", "{", "if", "(", "name", ".", "indexOf", "(", "'@'", ")", "<", "0", ")", "name", "+=", "'@'", "+", "state", ".", "parent", ".", "name", ";", "views", "[", "name", "]", "=", "view", ";", "}", ")", ";", "return", "views", ";", "}" ]
If there is no explicit multi-view configuration, make one up so we don't have to handle both cases in the view directive later. Note that having an explicit 'views' property will mean the default unnamed view properties are ignored. This is also a good time to resolve view names to absolute names, so everything is a straight lookup at link time.
[ "If", "there", "is", "no", "explicit", "multi", "-", "view", "configuration", "make", "one", "up", "so", "we", "don", "t", "have", "to", "handle", "both", "cases", "in", "the", "view", "directive", "later", ".", "Note", "that", "having", "an", "explicit", "views", "property", "will", "mean", "the", "default", "unnamed", "view", "properties", "are", "ignored", ".", "This", "is", "also", "a", "good", "time", "to", "resolve", "view", "names", "to", "absolute", "names", "so", "everything", "is", "a", "straight", "lookup", "at", "link", "time", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/state.js#L86-L94
9,488
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/state.js
handleRedirect
function handleRedirect(redirect, state, params, options) { /** * @ngdoc event * @name ui.router.state.$state#$stateNotFound * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when a requested state **cannot be found** using the provided state name during transition. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler, * you can see its three properties in the example. You can use `event.preventDefault()` to abort the * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value. * * @param {Object} event Event object. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties. * @param {State} fromState Current state object. * @param {Object} fromParams Current state params. * * @example * * <pre> * // somewhere, assume lazy.state has not been defined * $state.go("lazy.state", {a:1, b:2}, {inherit:false}); * * // somewhere else * $scope.$on('$stateNotFound', * function(event, unfoundState, fromState, fromParams){ * console.log(unfoundState.to); // "lazy.state" * console.log(unfoundState.toParams); // {a:1, b:2} * console.log(unfoundState.options); // {inherit:false} + default options * }) * </pre> */ var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params); if (evt.defaultPrevented) { $urlRouter.update(); return TransitionAborted; } if (!evt.retry) { return null; } // Allow the handler to return a promise to defer state lookup retry if (options.$retry) { $urlRouter.update(); return TransitionFailed; } var retryTransition = $state.transition = $q.when(evt.retry); retryTransition.then(function() { if (retryTransition !== $state.transition) return TransitionSuperseded; redirect.options.$retry = true; return $state.transitionTo(redirect.to, redirect.toParams, redirect.options); }, function() { return TransitionAborted; }); $urlRouter.update(); return retryTransition; }
javascript
function handleRedirect(redirect, state, params, options) { /** * @ngdoc event * @name ui.router.state.$state#$stateNotFound * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when a requested state **cannot be found** using the provided state name during transition. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler, * you can see its three properties in the example. You can use `event.preventDefault()` to abort the * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value. * * @param {Object} event Event object. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties. * @param {State} fromState Current state object. * @param {Object} fromParams Current state params. * * @example * * <pre> * // somewhere, assume lazy.state has not been defined * $state.go("lazy.state", {a:1, b:2}, {inherit:false}); * * // somewhere else * $scope.$on('$stateNotFound', * function(event, unfoundState, fromState, fromParams){ * console.log(unfoundState.to); // "lazy.state" * console.log(unfoundState.toParams); // {a:1, b:2} * console.log(unfoundState.options); // {inherit:false} + default options * }) * </pre> */ var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params); if (evt.defaultPrevented) { $urlRouter.update(); return TransitionAborted; } if (!evt.retry) { return null; } // Allow the handler to return a promise to defer state lookup retry if (options.$retry) { $urlRouter.update(); return TransitionFailed; } var retryTransition = $state.transition = $q.when(evt.retry); retryTransition.then(function() { if (retryTransition !== $state.transition) return TransitionSuperseded; redirect.options.$retry = true; return $state.transitionTo(redirect.to, redirect.toParams, redirect.options); }, function() { return TransitionAborted; }); $urlRouter.update(); return retryTransition; }
[ "function", "handleRedirect", "(", "redirect", ",", "state", ",", "params", ",", "options", ")", "{", "/**\n * @ngdoc event\n * @name ui.router.state.$state#$stateNotFound\n * @eventOf ui.router.state.$state\n * @eventType broadcast on root scope\n * @description\n * Fired when a requested state **cannot be found** using the provided state name during transition.\n * The event is broadcast allowing any handlers a single chance to deal with the error (usually by\n * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,\n * you can see its three properties in the example. You can use `event.preventDefault()` to abort the\n * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.\n *\n * @param {Object} event Event object.\n * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.\n * @param {State} fromState Current state object.\n * @param {Object} fromParams Current state params.\n *\n * @example\n *\n * <pre>\n * // somewhere, assume lazy.state has not been defined\n * $state.go(\"lazy.state\", {a:1, b:2}, {inherit:false});\n *\n * // somewhere else\n * $scope.$on('$stateNotFound',\n * function(event, unfoundState, fromState, fromParams){\n * console.log(unfoundState.to); // \"lazy.state\"\n * console.log(unfoundState.toParams); // {a:1, b:2}\n * console.log(unfoundState.options); // {inherit:false} + default options\n * })\n * </pre>\n */", "var", "evt", "=", "$rootScope", ".", "$broadcast", "(", "'$stateNotFound'", ",", "redirect", ",", "state", ",", "params", ")", ";", "if", "(", "evt", ".", "defaultPrevented", ")", "{", "$urlRouter", ".", "update", "(", ")", ";", "return", "TransitionAborted", ";", "}", "if", "(", "!", "evt", ".", "retry", ")", "{", "return", "null", ";", "}", "// Allow the handler to return a promise to defer state lookup retry", "if", "(", "options", ".", "$retry", ")", "{", "$urlRouter", ".", "update", "(", ")", ";", "return", "TransitionFailed", ";", "}", "var", "retryTransition", "=", "$state", ".", "transition", "=", "$q", ".", "when", "(", "evt", ".", "retry", ")", ";", "retryTransition", ".", "then", "(", "function", "(", ")", "{", "if", "(", "retryTransition", "!==", "$state", ".", "transition", ")", "return", "TransitionSuperseded", ";", "redirect", ".", "options", ".", "$retry", "=", "true", ";", "return", "$state", ".", "transitionTo", "(", "redirect", ".", "to", ",", "redirect", ".", "toParams", ",", "redirect", ".", "options", ")", ";", "}", ",", "function", "(", ")", "{", "return", "TransitionAborted", ";", "}", ")", ";", "$urlRouter", ".", "update", "(", ")", ";", "return", "retryTransition", ";", "}" ]
Handles the case where a state which is the target of a transition is not found, and the user can optionally retry or defer the transition
[ "Handles", "the", "case", "where", "a", "state", "which", "is", "the", "target", "of", "a", "transition", "is", "not", "found", "and", "the", "user", "can", "optionally", "retry", "or", "defer", "the", "transition" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/state.js#L713-L774
9,489
ionic-team/ng-cordova
demo/www/lib/angular-ui-router/src/urlMatcherFactory.js
getSquashPolicy
function getSquashPolicy(config, isOptional) { var squash = config.squash; if (!isOptional || squash === false) return false; if (!isDefined(squash) || squash == null) return defaultSquashPolicy; if (squash === true || isString(squash)) return squash; throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string"); }
javascript
function getSquashPolicy(config, isOptional) { var squash = config.squash; if (!isOptional || squash === false) return false; if (!isDefined(squash) || squash == null) return defaultSquashPolicy; if (squash === true || isString(squash)) return squash; throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string"); }
[ "function", "getSquashPolicy", "(", "config", ",", "isOptional", ")", "{", "var", "squash", "=", "config", ".", "squash", ";", "if", "(", "!", "isOptional", "||", "squash", "===", "false", ")", "return", "false", ";", "if", "(", "!", "isDefined", "(", "squash", ")", "||", "squash", "==", "null", ")", "return", "defaultSquashPolicy", ";", "if", "(", "squash", "===", "true", "||", "isString", "(", "squash", ")", ")", "return", "squash", ";", "throw", "new", "Error", "(", "\"Invalid squash policy: '\"", "+", "squash", "+", "\"'. Valid policies: false, true, or arbitrary string\"", ")", ";", "}" ]
returns false, true, or the squash value to indicate the "default parameter url squash policy".
[ "returns", "false", "true", "or", "the", "squash", "value", "to", "indicate", "the", "default", "parameter", "url", "squash", "policy", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/angular-ui-router/src/urlMatcherFactory.js#L923-L929
9,490
ionic-team/ng-cordova
src/plugins/bluetoothSerial.js
function (address) { var q = $q.defer(); $window.bluetoothSerial.connectInsecure(address, function () { q.resolve(); }, function (error) { q.reject(error); }); return q.promise; }
javascript
function (address) { var q = $q.defer(); $window.bluetoothSerial.connectInsecure(address, function () { q.resolve(); }, function (error) { q.reject(error); }); return q.promise; }
[ "function", "(", "address", ")", "{", "var", "q", "=", "$q", ".", "defer", "(", ")", ";", "$window", ".", "bluetoothSerial", ".", "connectInsecure", "(", "address", ",", "function", "(", ")", "{", "q", ".", "resolve", "(", ")", ";", "}", ",", "function", "(", "error", ")", "{", "q", ".", "reject", "(", "error", ")", ";", "}", ")", ";", "return", "q", ".", "promise", ";", "}" ]
not supported on iOS
[ "not", "supported", "on", "iOS" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/src/plugins/bluetoothSerial.js#L26-L34
9,491
ionic-team/ng-cordova
dist/ng-cordova.js
function (workout) { var q = $q.defer(); $window.plugins.healthkit.saveWorkout(workout, function (success) { q.resolve(success); }, function (err) { q.resolve(err); } ); return q.promise; }
javascript
function (workout) { var q = $q.defer(); $window.plugins.healthkit.saveWorkout(workout, function (success) { q.resolve(success); }, function (err) { q.resolve(err); } ); return q.promise; }
[ "function", "(", "workout", ")", "{", "var", "q", "=", "$q", ".", "defer", "(", ")", ";", "$window", ".", "plugins", ".", "healthkit", ".", "saveWorkout", "(", "workout", ",", "function", "(", "success", ")", "{", "q", ".", "resolve", "(", "success", ")", ";", "}", ",", "function", "(", "err", ")", "{", "q", ".", "resolve", "(", "err", ")", ";", "}", ")", ";", "return", "q", ".", "promise", ";", "}" ]
Save a workout. Workout param should be of the format: { 'activityType': 'HKWorkoutActivityTypeCycling', // HKWorkoutActivityType constant (https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKWorkout_Class/#//apple_ref/c/tdef/HKWorkoutActivityType) 'quantityType': 'HKQuantityTypeIdentifierDistanceCycling', 'startDate': new Date(), // mandatory 'endDate': null, // optional, use either this or duration 'duration': 3600, // in seconds, optional, use either this or endDate 'energy': 300, // 'energyUnit': 'kcal', // J|cal|kcal 'distance': 11, // optional 'distanceUnit': 'km' // probably useful with the former param 'extraData': "", // Not sure how necessary this is },
[ "Save", "a", "workout", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/dist/ng-cordova.js#L4451-L4462
9,492
ionic-team/ng-cordova
dist/ng-cordova.js
function (promise){ promise.success = function (fn) { promise.then(fn); return promise; }; promise.error = function (fn) { promise.then(null, fn); return promise; }; }
javascript
function (promise){ promise.success = function (fn) { promise.then(fn); return promise; }; promise.error = function (fn) { promise.then(null, fn); return promise; }; }
[ "function", "(", "promise", ")", "{", "promise", ".", "success", "=", "function", "(", "fn", ")", "{", "promise", ".", "then", "(", "fn", ")", ";", "return", "promise", ";", "}", ";", "promise", ".", "error", "=", "function", "(", "fn", ")", "{", "promise", ".", "then", "(", "null", ",", "fn", ")", ";", "return", "promise", ";", "}", ";", "}" ]
Decorate the promise object. @param promise The promise object.
[ "Decorate", "the", "promise", "object", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/dist/ng-cordova.js#L6040-L6050
9,493
ionic-team/ng-cordova
dist/ng-cordova.js
function (key, value, dict) { var deferred = $q.defer(); var promise = deferred.promise; function ok(value){ deferred.resolve(value); } function errorCallback(error){ deferred.reject(new Error(error)); } if($window.plugins){ var storeResult; if(arguments.length === 3){ storeResult = $window.plugins.appPreferences.store(dict, key, value); } else { storeResult = $window.plugins.appPreferences.store(key, value); } storeResult.then(ok, errorCallback); } else { deferred.reject(new Error(this.pluginNotEnabledMessage)); } this.decoratePromise(promise); return promise; }
javascript
function (key, value, dict) { var deferred = $q.defer(); var promise = deferred.promise; function ok(value){ deferred.resolve(value); } function errorCallback(error){ deferred.reject(new Error(error)); } if($window.plugins){ var storeResult; if(arguments.length === 3){ storeResult = $window.plugins.appPreferences.store(dict, key, value); } else { storeResult = $window.plugins.appPreferences.store(key, value); } storeResult.then(ok, errorCallback); } else { deferred.reject(new Error(this.pluginNotEnabledMessage)); } this.decoratePromise(promise); return promise; }
[ "function", "(", "key", ",", "value", ",", "dict", ")", "{", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "var", "promise", "=", "deferred", ".", "promise", ";", "function", "ok", "(", "value", ")", "{", "deferred", ".", "resolve", "(", "value", ")", ";", "}", "function", "errorCallback", "(", "error", ")", "{", "deferred", ".", "reject", "(", "new", "Error", "(", "error", ")", ")", ";", "}", "if", "(", "$window", ".", "plugins", ")", "{", "var", "storeResult", ";", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "storeResult", "=", "$window", ".", "plugins", ".", "appPreferences", ".", "store", "(", "dict", ",", "key", ",", "value", ")", ";", "}", "else", "{", "storeResult", "=", "$window", ".", "plugins", ".", "appPreferences", ".", "store", "(", "key", ",", "value", ")", ";", "}", "storeResult", ".", "then", "(", "ok", ",", "errorCallback", ")", ";", "}", "else", "{", "deferred", ".", "reject", "(", "new", "Error", "(", "this", ".", "pluginNotEnabledMessage", ")", ")", ";", "}", "this", ".", "decoratePromise", "(", "promise", ")", ";", "return", "promise", ";", "}" ]
Store the value of the given dictionary and key. @param key The key of the preference. @param value The value to set. @param dict The dictionary. It's optional. @returns Returns a promise.
[ "Store", "the", "value", "of", "the", "given", "dictionary", "and", "key", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/dist/ng-cordova.js#L6059-L6086
9,494
ionic-team/ng-cordova
dist/ng-cordova.js
function () { var deferred = $q.defer(); var promise = deferred.promise; function ok(value){ deferred.resolve(value); } function errorCallback(error){ deferred.reject(new Error(error)); } if($window.plugins){ $window.plugins.appPreferences.show() .then(ok, errorCallback); } else { deferred.reject(new Error(this.pluginNotEnabledMessage)); } this.decoratePromise(promise); return promise; }
javascript
function () { var deferred = $q.defer(); var promise = deferred.promise; function ok(value){ deferred.resolve(value); } function errorCallback(error){ deferred.reject(new Error(error)); } if($window.plugins){ $window.plugins.appPreferences.show() .then(ok, errorCallback); } else { deferred.reject(new Error(this.pluginNotEnabledMessage)); } this.decoratePromise(promise); return promise; }
[ "function", "(", ")", "{", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "var", "promise", "=", "deferred", ".", "promise", ";", "function", "ok", "(", "value", ")", "{", "deferred", ".", "resolve", "(", "value", ")", ";", "}", "function", "errorCallback", "(", "error", ")", "{", "deferred", ".", "reject", "(", "new", "Error", "(", "error", ")", ")", ";", "}", "if", "(", "$window", ".", "plugins", ")", "{", "$window", ".", "plugins", ".", "appPreferences", ".", "show", "(", ")", ".", "then", "(", "ok", ",", "errorCallback", ")", ";", "}", "else", "{", "deferred", ".", "reject", "(", "new", "Error", "(", "this", ".", "pluginNotEnabledMessage", ")", ")", ";", "}", "this", ".", "decoratePromise", "(", "promise", ")", ";", "return", "promise", ";", "}" ]
Show the application preferences. @returns Returns a promise.
[ "Show", "the", "application", "preferences", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/dist/ng-cordova.js#L6160-L6181
9,495
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
triggerEvent
function triggerEvent(gesture, eventData){ // create DOM event var event = ionic.Gestures.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(ionic.Gestures.utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }
javascript
function triggerEvent(gesture, eventData){ // create DOM event var event = ionic.Gestures.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(ionic.Gestures.utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }
[ "function", "triggerEvent", "(", "gesture", ",", "eventData", ")", "{", "// create DOM event", "var", "event", "=", "ionic", ".", "Gestures", ".", "DOCUMENT", ".", "createEvent", "(", "'Event'", ")", ";", "event", ".", "initEvent", "(", "gesture", ",", "true", ",", "true", ")", ";", "event", ".", "gesture", "=", "eventData", ";", "// trigger on the target if it is in the instance element,", "// this is for event delegation tricks", "var", "element", "=", "this", ".", "element", ";", "if", "(", "ionic", ".", "Gestures", ".", "utils", ".", "hasParent", "(", "eventData", ".", "target", ",", "element", ")", ")", "{", "element", "=", "eventData", ".", "target", ";", "}", "element", ".", "dispatchEvent", "(", "event", ")", ";", "return", "this", ";", "}" ]
trigger gesture event @param {String} gesture @param {Object} eventData @returns {ionic.Gestures.Instance}
[ "trigger", "gesture", "event" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L785-L800
9,496
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
getDirection
function getDirection(touch1, touch2) { var x = Math.abs(touch1.pageX - touch2.pageX), y = Math.abs(touch1.pageY - touch2.pageY); if(x >= y) { return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } else { return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } }
javascript
function getDirection(touch1, touch2) { var x = Math.abs(touch1.pageX - touch2.pageX), y = Math.abs(touch1.pageY - touch2.pageY); if(x >= y) { return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } else { return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } }
[ "function", "getDirection", "(", "touch1", ",", "touch2", ")", "{", "var", "x", "=", "Math", ".", "abs", "(", "touch1", ".", "pageX", "-", "touch2", ".", "pageX", ")", ",", "y", "=", "Math", ".", "abs", "(", "touch1", ".", "pageY", "-", "touch2", ".", "pageY", ")", ";", "if", "(", "x", ">=", "y", ")", "{", "return", "touch1", ".", "pageX", "-", "touch2", ".", "pageX", ">", "0", "?", "ionic", ".", "Gestures", ".", "DIRECTION_LEFT", ":", "ionic", ".", "Gestures", ".", "DIRECTION_RIGHT", ";", "}", "else", "{", "return", "touch1", ".", "pageY", "-", "touch2", ".", "pageY", ">", "0", "?", "ionic", ".", "Gestures", ".", "DIRECTION_UP", ":", "ionic", ".", "Gestures", ".", "DIRECTION_DOWN", ";", "}", "}" ]
angle to direction define @param {Touch} touch1 @param {Touch} touch2 @returns {String} direction constant, like ionic.Gestures.DIRECTION_LEFT
[ "angle", "to", "direction", "define" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L1227-L1237
9,497
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
isVertical
function isVertical(direction) { return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN); }
javascript
function isVertical(direction) { return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN); }
[ "function", "isVertical", "(", "direction", ")", "{", "return", "(", "direction", "==", "ionic", ".", "Gestures", ".", "DIRECTION_UP", "||", "direction", "==", "ionic", ".", "Gestures", ".", "DIRECTION_DOWN", ")", ";", "}" ]
boolean if the direction is vertical @param {String} direction @returns {Boolean} is_vertical
[ "boolean", "if", "the", "direction", "is", "vertical" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L1291-L1293
9,498
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
stopDefaultBrowserBehavior
function stopDefaultBrowserBehavior(element, css_class) { // changed from making many style changes to just adding a preset classname // less DOM manipulations, less code, and easier to control in the CSS side of things // hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method if(element && element.classList) { element.classList.add(css_class); element.onselectstart = function() { return false; }; } }
javascript
function stopDefaultBrowserBehavior(element, css_class) { // changed from making many style changes to just adding a preset classname // less DOM manipulations, less code, and easier to control in the CSS side of things // hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method if(element && element.classList) { element.classList.add(css_class); element.onselectstart = function() { return false; }; } }
[ "function", "stopDefaultBrowserBehavior", "(", "element", ",", "css_class", ")", "{", "// changed from making many style changes to just adding a preset classname", "// less DOM manipulations, less code, and easier to control in the CSS side of things", "// hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method", "if", "(", "element", "&&", "element", ".", "classList", ")", "{", "element", ".", "classList", ".", "add", "(", "css_class", ")", ";", "element", ".", "onselectstart", "=", "function", "(", ")", "{", "return", "false", ";", "}", ";", "}", "}" ]
stop browser default behavior with css class @param {HtmlElement} element @param {Object} css_class
[ "stop", "browser", "default", "behavior", "with", "css", "class" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L1301-L1311
9,499
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
detect
function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // instance options var inst_options = this.current.inst.options; // call ionic.Gestures.gesture handlers for(var g=0,len=this.gestures.length; g<len; g++) { var gesture = this.gestures[g]; // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, this.current.inst) === false) { this.stopDetect(); break; } } } // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // endevent, but not the last touch, so dont stop if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length-1) { this.stopDetect(); } return eventData; }
javascript
function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // instance options var inst_options = this.current.inst.options; // call ionic.Gestures.gesture handlers for(var g=0,len=this.gestures.length; g<len; g++) { var gesture = this.gestures[g]; // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, this.current.inst) === false) { this.stopDetect(); break; } } } // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // endevent, but not the last touch, so dont stop if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length-1) { this.stopDetect(); } return eventData; }
[ "function", "detect", "(", "eventData", ")", "{", "if", "(", "!", "this", ".", "current", "||", "this", ".", "stopped", ")", "{", "return", ";", "}", "// extend event data with calculations about scale, distance etc", "eventData", "=", "this", ".", "extendEventData", "(", "eventData", ")", ";", "// instance options", "var", "inst_options", "=", "this", ".", "current", ".", "inst", ".", "options", ";", "// call ionic.Gestures.gesture handlers", "for", "(", "var", "g", "=", "0", ",", "len", "=", "this", ".", "gestures", ".", "length", ";", "g", "<", "len", ";", "g", "++", ")", "{", "var", "gesture", "=", "this", ".", "gestures", "[", "g", "]", ";", "// only when the instance options have enabled this gesture", "if", "(", "!", "this", ".", "stopped", "&&", "inst_options", "[", "gesture", ".", "name", "]", "!==", "false", ")", "{", "// if a handler returns false, we stop with the detection", "if", "(", "gesture", ".", "handler", ".", "call", "(", "gesture", ",", "eventData", ",", "this", ".", "current", ".", "inst", ")", "===", "false", ")", "{", "this", ".", "stopDetect", "(", ")", ";", "break", ";", "}", "}", "}", "// store as previous event event", "if", "(", "this", ".", "current", ")", "{", "this", ".", "current", ".", "lastEvent", "=", "eventData", ";", "}", "// endevent, but not the last touch, so dont stop", "if", "(", "eventData", ".", "eventType", "==", "ionic", ".", "Gestures", ".", "EVENT_END", "&&", "!", "eventData", ".", "touches", ".", "length", "-", "1", ")", "{", "this", ".", "stopDetect", "(", ")", ";", "}", "return", "eventData", ";", "}" ]
ionic.Gestures.gesture detection @param {Object} eventData
[ "ionic", ".", "Gestures", ".", "gesture", "detection" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L1358-L1394