_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q45700
|
ComplexAspect
|
train
|
function ComplexAspect(complexObject, parent, parentProperty) {
if (!complexObject) {
throw new Error("The ComplexAspect ctor requires an entity as its only argument.");
}
if (complexObject.complexAspect) {
return complexObject.complexAspect;
}
// if called without new
if (!(this instanceof ComplexAspect)) {
return new ComplexAspect(complexObject, parent, parentProperty);
}
// entityType should already be on the entity from 'watch'
this.complexObject = complexObject;
complexObject.complexAspect = this;
// TODO: keep public or not?
this.originalValues = {};
// if a standalone complexObject
if (parent != null) {
this.parent = parent;
this.parentProperty = parentProperty;
}
var complexType = complexObject.complexType;
if (!complexType) {
var typeName = complexObject.prototype._$typeName;
if (!typeName) {
throw new Error("This entity is not registered as a valid ComplexType");
} else {
throw new Error("Metadata for this complexType has not yet been resolved: " + typeName);
}
}
var complexCtor = complexType.getCtor();
__modelLibraryDef.getDefaultInstance().startTracking(complexObject, complexCtor.prototype);
}
|
javascript
|
{
"resource": ""
}
|
q45701
|
EntityKey
|
train
|
function EntityKey(entityType, keyValues) {
assertParam(entityType, "entityType").isInstanceOf(EntityType).check();
var subtypes = entityType.getSelfAndSubtypes();
if (subtypes.length > 1) {
this._subtypes = subtypes.filter(function (st) {
return st.isAbstract === false;
});
}
if (!Array.isArray(keyValues)) {
keyValues = __arraySlice(arguments, 1);
}
this.entityType = entityType;
entityType.keyProperties.forEach(function (kp, i) {
// insure that guid keys are comparable.
if (kp.dataType === DataType.Guid) {
keyValues[i] = keyValues[i] && keyValues[i].toLowerCase();
}
});
this.values = keyValues;
this._keyInGroup = createKeyString(keyValues);
}
|
javascript
|
{
"resource": ""
}
|
q45702
|
JsonResultsAdapter
|
train
|
function JsonResultsAdapter(config) {
if (arguments.length !== 1) {
throw new Error("The JsonResultsAdapter ctor should be called with a single argument that is a configuration object.");
}
assertConfig(config)
.whereParam("name").isNonEmptyString()
.whereParam("extractResults").isFunction().isOptional().withDefault(extractResultsDefault)
.whereParam("extractSaveResults").isFunction().isOptional().withDefault(extractSaveResultsDefault)
.whereParam("extractKeyMappings").isFunction().isOptional().withDefault(extractKeyMappingsDefault)
.whereParam("extractDeletedKeys").isFunction().isOptional().withDefault(extractDeletedKeysDefault)
.whereParam("visitNode").isFunction()
.applyAll(this);
__config._storeObject(this, proto._$typeName, this.name);
}
|
javascript
|
{
"resource": ""
}
|
q45703
|
LocalQueryComparisonOptions
|
train
|
function LocalQueryComparisonOptions(config) {
assertConfig(config || {})
.whereParam("name").isOptional().isString()
.whereParam("isCaseSensitive").isOptional().isBoolean()
.whereParam("usesSql92CompliantStringComparison").isBoolean()
.applyAll(this);
if (!this.name) {
this.name = __getUuid();
}
__config._storeObject(this, proto._$typeName, this.name);
}
|
javascript
|
{
"resource": ""
}
|
q45704
|
NamingConvention
|
train
|
function NamingConvention(config) {
assertConfig(config || {})
.whereParam("name").isOptional().isString()
.whereParam("serverPropertyNameToClient").isFunction()
.whereParam("clientPropertyNameToServer").isFunction()
.applyAll(this);
if (!this.name) {
this.name = __getUuid();
}
__config._storeObject(this, proto._$typeName, this.name);
}
|
javascript
|
{
"resource": ""
}
|
q45705
|
train
|
function () {
// empty ctor is used by all subclasses.
if (arguments.length === 0) return;
if (arguments.length === 1) {
// 3 possibilities:
// Predicate(aPredicate)
// Predicate([ aPredicate ])
// Predicate(["freight", ">", 100"])
// Predicate( "freight gt 100" } // passthru ( i.e. maybe an odata string)
// Predicate( { freight: { ">": 100 } })
var arg = arguments[0];
if (Array.isArray(arg)) {
if (arg.length === 1) {
// recurse
return Predicate(arg[0]);
} else {
return createPredicateFromArray(arg);
}
} else if (arg instanceof Predicate) {
return arg;
} else if (typeof arg == 'string') {
return new PassthruPredicate(arg);
} else {
return createPredicateFromObject(arg);
}
} else {
// 2 possibilities
// Predicate("freight", ">", 100");
// Predicate("orders", "any", "freight", ">", 950);
return createPredicateFromArray(Array.prototype.slice.call(arguments, 0));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45706
|
getPropertyPathValue
|
train
|
function getPropertyPathValue(obj, propertyPath) {
var properties = Array.isArray(propertyPath) ? propertyPath : propertyPath.split(".");
if (properties.length === 1) {
return obj.getProperty(propertyPath);
} else {
var nextValue = obj;
// hack use of some to perform mapFirst operation.
properties.some(function (prop) {
nextValue = nextValue.getProperty(prop);
return nextValue == null;
});
return nextValue;
}
}
|
javascript
|
{
"resource": ""
}
|
q45707
|
EntityManager
|
train
|
function EntityManager(config) {
if (arguments.length > 1) {
throw new Error("The EntityManager ctor has a single optional argument that is either a 'serviceName' or a configuration object.");
}
if (arguments.length === 0) {
config = { serviceName: "" };
} else if (typeof config === 'string') {
config = { serviceName: config };
}
updateWithConfig(this, config, true);
this.entityChanged = new Event("entityChanged", this);
this.validationErrorsChanged = new Event("validationErrorsChanged", this);
this.hasChangesChanged = new Event("hasChangesChanged", this);
this.clear();
}
|
javascript
|
{
"resource": ""
}
|
q45708
|
checkEntityTypes
|
train
|
function checkEntityTypes(em, entityTypes) {
assertParam(entityTypes, "entityTypes").isString().isOptional().or().isNonEmptyArray().isString()
.or().isInstanceOf(EntityType).or().isNonEmptyArray().isInstanceOf(EntityType).check();
if (typeof entityTypes === "string") {
entityTypes = em.metadataStore._getEntityType(entityTypes, false);
} else if (Array.isArray(entityTypes) && typeof entityTypes[0] === "string") {
entityTypes = entityTypes.map(function (etName) {
return em.metadataStore._getEntityType(etName, false);
});
}
return entityTypes;
}
|
javascript
|
{
"resource": ""
}
|
q45709
|
mergeEntity
|
train
|
function mergeEntity(mc, node, meta) {
node._$meta = meta;
var em = mc.entityManager;
var entityType = meta.entityType;
if (typeof (entityType) === 'string') {
entityType = mc.metadataStore._getEntityType(entityType, false);
}
node.entityType = entityType;
var mergeStrategy = mc.mergeOptions.mergeStrategy;
var isSaving = mc.query == null;
var entityKey = entityType.getEntityKeyFromRawEntity(node, mc.rawValueFn);
var targetEntity = em.findEntityByKey(entityKey);
if (targetEntity) {
if (isSaving && targetEntity.entityAspect.entityState.isDeleted()) {
em.detachEntity(targetEntity);
return targetEntity;
}
var targetEntityState = targetEntity.entityAspect.entityState;
if (mergeStrategy === MergeStrategy.Disallowed) {
throw new Error("A MergeStrategy of 'Disallowed' prevents " + entityKey.toString() + " from being merged");
} else if (mergeStrategy === MergeStrategy.SkipMerge) {
updateEntityNoMerge(mc, targetEntity, node);
} else {
if (mergeStrategy === MergeStrategy.OverwriteChanges
|| targetEntityState.isUnchanged()) {
updateEntity(mc, targetEntity, node);
targetEntity.entityAspect.wasLoaded = true;
if (meta.extraMetadata) {
targetEntity.entityAspect.extraMetadata = meta.extraMetadata;
}
targetEntity.entityAspect.entityState = EntityState.Unchanged;
clearOriginalValues(targetEntity);
targetEntity.entityAspect.propertyChanged.publish({ entity: targetEntity, propertyName: null });
var action = isSaving ? EntityAction.MergeOnSave : EntityAction.MergeOnQuery;
em.entityChanged.publish({ entityAction: action, entity: targetEntity });
// this is needed to handle an overwrite of a modified entity with an unchanged entity
// which might in turn cause _hasChanges to change.
if (!targetEntityState.isUnchanged()) {
em._notifyStateChange(targetEntity, false);
}
} else {
if (targetEntityState == EntityState.Deleted && !mc.mergeOptions.includeDeleted) {
return null;
}
updateEntityNoMerge(mc, targetEntity, node);
}
}
} else {
targetEntity = entityType._createInstanceCore();
updateEntity(mc, targetEntity, node);
if (meta.extraMetadata) {
targetEntity.entityAspect.extraMetadata = meta.extraMetadata;
}
// em._attachEntityCore(targetEntity, EntityState.Unchanged, MergeStrategy.Disallowed);
em._attachEntityCore(targetEntity, EntityState.Unchanged, mergeStrategy);
targetEntity.entityAspect.wasLoaded = true;
em.entityChanged.publish({ entityAction: EntityAction.AttachOnQuery, entity: targetEntity });
}
return targetEntity;
}
|
javascript
|
{
"resource": ""
}
|
q45710
|
DefaultChangeRequestInterceptor
|
train
|
function DefaultChangeRequestInterceptor(saveContext, saveBundle) {
/**
Prepare and return the save data for an entity change-set.
The adapter calls this method for each entity in the change-set,
after it has prepared a "change request" for that object.
The method can do anything to the request but it must return a valid, non-null request.
@example
this.getRequest = function (request, entity, index) {
// alter the request that the adapter prepared for this entity
// based on the entity, saveContext, and saveBundle
// e.g., add a custom header or prune the originalValuesMap
return request;
};
@method getRequest
@param request {Object} The object representing the adapter's request to save this entity.
@param entity {Entity} The entity-to-be-save as it is in cache
@param index {Integer} The zero-based index of this entity in the change-set array
@return {Function} The potentially revised request.
**/
this.getRequest = function (request, entity, index) {
return request;
};
/**
Last chance to change anything about the 'requests' array
after it has been built with requests for all of the entities-to-be-saved.
The 'requests' array is the same as 'saveBundle.entities' in many implementations
This method can do anything to the array including add and remove requests.
It's up to you to ensure that server will accept the requests array data as valid.
Returned value is ignored.
@example
this.done = function (requests) {
// alter the array of requests representing the entire change-set
// based on the saveContext and saveBundle
};
@method done
@param requests {Array of Object} The adapter's array of request for this changeset.
**/
this.done = function (requests) {
};
}
|
javascript
|
{
"resource": ""
}
|
q45711
|
toQueryString
|
train
|
function toQueryString(obj) {
var parts = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
}
}
return parts.join("&");
}
|
javascript
|
{
"resource": ""
}
|
q45712
|
movePropDefsToProto
|
train
|
function movePropDefsToProto(proto) {
var stype = proto.entityType || proto.complexType;
var extra = stype._extra;
var alreadyWrapped = extra.alreadyWrappedProps || {};
stype.getProperties().forEach(function (prop) {
var propName = prop.name;
// we only want to wrap props that haven't already been wrapped
if (alreadyWrapped[propName]) return;
// If property is already defined on the prototype then wrap it in another propertyDescriptor.
// otherwise create a propDescriptor for it.
var descr;
if (propName in proto) {
descr = wrapPropDescription(proto, prop);
} else {
descr = makePropDescription(proto, prop);
}
// descr will be null for a wrapped descr that is not configurable
if (descr != null) {
Object.defineProperty(proto, propName, descr);
}
alreadyWrapped[propName] = true;
});
extra.alreadyWrappedProps = alreadyWrapped;
}
|
javascript
|
{
"resource": ""
}
|
q45713
|
movePropsToBackingStore
|
train
|
function movePropsToBackingStore(instance) {
var bs = getBackingStore(instance);
var proto = Object.getPrototypeOf(instance);
var stype = proto.entityType || proto.complexType;
stype.getProperties().forEach(function (prop) {
var propName = prop.name;
if (prop.isUnmapped) {
// insure that any unmapped properties that were added after entityType
// was first created are wrapped with a property descriptor.
if (!core.getPropertyDescriptor(proto, propName)) {
var descr = makePropDescription(proto, prop);
Object.defineProperty(proto, propName, descr);
}
}
if (!instance.hasOwnProperty(propName)) return;
// pulls off the value, removes the instance property and then rewrites it via ES5 accessor
var value = instance[propName];
delete instance[propName];
instance[propName] = value;
});
return bs;
}
|
javascript
|
{
"resource": ""
}
|
q45714
|
getPendingBackingStore
|
train
|
function getPendingBackingStore(instance) {
var proto = Object.getPrototypeOf(instance);
var pendingStores = proto._pendingBackingStores;
var pending = core.arrayFirst(pendingStores, function (pending) {
return pending.entity === instance;
});
if (pending) return pending.backingStore;
var bs = {};
pendingStores.push({ entity: instance, backingStore: bs });
return bs;
}
|
javascript
|
{
"resource": ""
}
|
q45715
|
font
|
train
|
function font() {
return src([`${svgDir}/*.svg`])
.pipe(
iconfontCss({
fontName: config.name,
path: template,
targetPath: '../src/index.less',
normalize: true,
firstGlyph: 0xf000,
cssClass: fontName // this is a trick to pass fontName to template
})
)
.pipe(
iconfont({
fontName,
formats
})
)
.pipe(dest(srcDir));
}
|
javascript
|
{
"resource": ""
}
|
q45716
|
train
|
function(imageData, options, success, error) {
exec(
success,
error,
'OpenALPR',
'scan',
[imageData, validateOptions(options)]
)
}
|
javascript
|
{
"resource": ""
}
|
|
q45717
|
validateOptions
|
train
|
function validateOptions(options) {
//Check if options is set and is an object.
if(! options || ! typeof options === 'object') {
return {
country: DEFAULT_COUNTRY,
amount: DEFAULT_AMOUNT
}
}
//Check if country property is set.
if (! options.hasOwnProperty('country')) {
options.country = DEFAULT_COUNTRY;
}
//Check if amount property is set.
if (! options.hasOwnProperty('amount')) {
options.amount = DEFAULT_AMOUNT;
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
q45718
|
deserialize
|
train
|
function deserialize (rawData) {
return JSON.parse(rawData, function (k, v) {
if (k === '$$date') { return new Date(v); }
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null) { return v; }
if (v && v.$$date) { return v.$$date; }
if (v && v.$$regex) { return deserializeRegex(v.$$regex) }
return v;
});
}
|
javascript
|
{
"resource": ""
}
|
q45719
|
compoundCompareThings
|
train
|
function compoundCompareThings (fields) {
return function (a, b) {
var i, len, comparison;
// undefined
if (a === undefined) { return b === undefined ? 0 : -1; }
if (b === undefined) { return a === undefined ? 0 : 1; }
// null
if (a === null) { return b === null ? 0 : -1; }
if (b === null) { return a === null ? 0 : 1; }
for (i = 0, len = fields.length; i < len; i++) {
comparison = compareThings(a[fields[i]], b[fields[i]]);
if (comparison !== 0) { return comparison; }
}
return 0;
};
}
|
javascript
|
{
"resource": ""
}
|
q45720
|
modify
|
train
|
function modify (obj, updateQuery) {
var keys = Object.keys(updateQuery)
, firstChars = _.map(keys, function (item) { return item[0]; })
, dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; })
, newDoc, modifiers
;
if ((keys.indexOf('_id') !== -1) && (updateQuery._id !== obj._id)) { throw "You cannot change a document's _id"; }
if ((dollarFirstChars.length !== 0) && (dollarFirstChars.length !== firstChars.length)) {
throw "You cannot mix modifiers and normal fields";
}
if (dollarFirstChars.length === 0) {
// Simply replace the object with the update query contents
newDoc = deepCopy(updateQuery);
newDoc._id = obj._id;
} else {
// Apply modifiers
modifiers = _.uniq(keys);
newDoc = deepCopy(obj);
modifiers.forEach(function (m) {
var keys;
if (!modifierFunctions[m]) { throw "Unknown modifier " + m; }
try {
keys = Object.keys(updateQuery[m]);
} catch (e) {
throw "Modifier " + m + "'s argument must be an object";
}
keys.forEach(function (k) {
modifierFunctions[m](newDoc, k, updateQuery[m][k]);
});
});
}
// Check result is valid and return it
checkObject(newDoc);
if (obj._id !== newDoc._id) { throw "You can't change a document's _id"; }
return newDoc;
}
|
javascript
|
{
"resource": ""
}
|
q45721
|
match
|
train
|
function match (obj, query) {
var queryKeys, queryKey, queryValue, i;
// Primitive query against a primitive type
// This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later
// But I don't have time for a cleaner implementation now
if (isPrimitiveType(obj) || isPrimitiveType(query)) {
return matchQueryPart({ needAKey: obj }, 'needAKey', query);
}
// Normal query
queryKeys = Object.keys(query);
for (i = 0; i < queryKeys.length; i += 1) {
queryKey = queryKeys[i];
queryValue = query[queryKey];
if (queryKey[0] === '$') {
if (!logicalOperators[queryKey]) { throw "Unknown logical operator " + queryKey; }
if (!logicalOperators[queryKey](obj, queryValue)) { return false; }
} else {
if (!matchQueryPart(obj, queryKey, queryValue)) { return false; }
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q45722
|
projectForUnique
|
train
|
function projectForUnique (elt) {
if (elt === null) { return '$null'; }
if (typeof elt === 'string') { return '$string' + elt; }
if (typeof elt === 'boolean') { return '$boolean' + elt; }
if (typeof elt === 'number') { return '$number' + elt; }
if (util.isArray(elt)) { return '$date' + elt.getTime(); }
return elt; // Arrays and ob
}
|
javascript
|
{
"resource": ""
}
|
q45723
|
getDotValues
|
train
|
function getDotValues (doc, fields) {
var field, key, i, len;
if (util.isArray(fields)) {
key = {};
for (i = 0, len = fields.length; i < len; i++) {
field = fields[i];
key[field] = document.getDotValue(doc, field);
}
return key;
} else {
return document.getDotValue(doc, fields);
}
}
|
javascript
|
{
"resource": ""
}
|
q45724
|
Model
|
train
|
function Model (name, schema, options) {
if (typeof(name) != "string") throw "model name must be provided and a string";
if (arguments.length==1) { options = {}; schema = {} };
if (arguments.length==2) { options = schema; schema = {} };
var self = function Document(raw) { return document.Document.call(this, self, raw) }; // Call the Document builder
_.extend(self, Model.prototype); // Ugly but works - we need to return a function but still inherit prototype
var emitter = new events.EventEmitter();
emitter.setMaxListeners(0);
for (var prop in emitter) self[prop] = emitter[prop];
self.modelName = name;
self.schema = schemas.normalize(Object.assign({}, schema)); // Normalize to allow for short-hands
self.filename = path.normalize(options.filename || path.join(Model.dbPath || ".", name+".db"));
self.options = _.extend({}, Model.defaults, options);
// Indexed by field name, dot notation can be used
// _id is always indexed and since _ids are generated randomly the underlying
// binary is always well-balanced
self.indexes = {};
self.indexes._id = new Index({ fieldName: '_id', unique: true });
schemas.indexes(schema).forEach(function(idx) { self.ensureIndex(idx) });
// Concurrency control for 1) index building and 2) pulling objects from LevelUP
self._pipe = new bagpipe(1);
self._pipe.pause();
self._retrQueue = new bagpipe(LEVELUP_RETR_CONCURRENCY);
self._retrQueue._locked = {}; self._retrQueue._locks = {}; // Hide those in ._retrQueue
self._methods = {};
if (self.options.autoLoad) self.initStore();
return self;
}
|
javascript
|
{
"resource": ""
}
|
q45725
|
updated
|
train
|
function updated(docs) {
// Refresh if any of the objects: have an ID which is in our results OR they match our query (this.query)
var shouldRefresh = false;
docs.forEach(function(doc) { // Avoid using .some since it would stop iterating after first match and we need to set _prefetched
var interested = self._count || self._ids[doc._id] || document.match(doc, self.query); // _count queries never set _ids
if (interested) self._prefetched[doc._id] = doc;
shouldRefresh = shouldRefresh || interested;
});
if (shouldRefresh) refresh();
}
|
javascript
|
{
"resource": ""
}
|
q45726
|
isCheckedOut
|
train
|
async function isCheckedOut(dir, ref) {
let oidCurrent;
return git.resolveRef({ dir, ref: 'HEAD' })
.then((oid) => {
oidCurrent = oid;
return git.resolveRef({ dir, ref });
})
.then(oid => oidCurrent === oid)
.catch(() => false);
}
|
javascript
|
{
"resource": ""
}
|
q45727
|
resolveCommit
|
train
|
async function resolveCommit(dir, ref) {
return git.resolveRef({ dir, ref })
.catch(async (err) => {
if (err.code === 'ResolveRefError') {
// fallback: is ref a shortened oid prefix?
const oid = await git.expandOid({ dir, oid: ref }).catch(() => { throw err; });
return git.resolveRef({ dir, ref: oid });
}
// re-throw
throw err;
});
}
|
javascript
|
{
"resource": ""
}
|
q45728
|
resolveBlob
|
train
|
async function resolveBlob(dir, ref, pathName, includeUncommitted) {
const commitSha = await resolveCommit(dir, ref);
// project-helix/#150: check for uncommitted local changes
// project-helix/#183: serve newly created uncommitted files
// project-helix/#187: only serve uncommitted content if currently
// checked-out and requested refs match
if (!includeUncommitted) {
return (await git.readObject({ dir, oid: commitSha, filepath: pathName })).oid;
}
// check working dir status
const status = await git.status({ dir, filepath: pathName });
if (status.endsWith('unmodified')) {
return (await git.readObject({ dir, oid: commitSha, filepath: pathName })).oid;
}
if (status.endsWith('absent') || status.endsWith('deleted')) {
const err = new Error(`Not found: ${pathName}`);
err.code = git.E.TreeOrBlobNotFoundError;
throw err;
}
// return blob id representing working dir file
const content = await fse.readFile(resolvePath(dir, pathName));
return git.writeObject({
dir,
object: content,
type: 'blob',
format: 'content',
});
}
|
javascript
|
{
"resource": ""
}
|
q45729
|
getRawContent
|
train
|
async function getRawContent(dir, ref, pathName, includeUncommitted) {
return resolveBlob(dir, ref, pathName, includeUncommitted)
.then(oid => git.readObject({ dir, oid, format: 'content' }).object);
}
|
javascript
|
{
"resource": ""
}
|
q45730
|
createBlobReadStream
|
train
|
async function createBlobReadStream(dir, oid) {
const { object: content } = await git.readObject({ dir, oid });
const stream = new PassThrough();
stream.end(content);
return stream;
}
|
javascript
|
{
"resource": ""
}
|
q45731
|
isValidSha
|
train
|
function isValidSha(str) {
if (typeof str === 'string' && str.length === 40) {
const res = str.match(/[0-9a-f]/g);
return res && res.length === 40;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q45732
|
commitLog
|
train
|
async function commitLog(dir, ref, path) {
return git.log({ dir, ref, path })
.catch(async (err) => {
if (err.code === 'ResolveRefError') {
// fallback: is ref a shortened oid prefix?
const oid = await git.expandOid({ dir, oid: ref });
return git.log({ dir, ref: oid, path });
}
// re-throw
throw err;
})
.then(async (commits) => {
if (typeof path === 'string' && path.length) {
// filter by path
let lastSHA = null;
let lastCommit = null;
const filteredCommits = [];
for (let i = 0; i < commits.length; i += 1) {
const commit = commits[i];
/* eslint-disable no-await-in-loop */
try {
const o = await git.readObject({ dir, oid: commit.oid, filepath: path });
if (i === commits.length - 1) {
// file already existed in first commit
filteredCommits.push(commit);
break;
}
if (o.oid !== lastSHA) {
if (lastSHA !== null) {
filteredCommits.push(lastCommit);
}
lastSHA = o.oid;
}
} catch (err) {
// file no longer there
filteredCommits.push(lastCommit);
break;
}
lastCommit = commit;
}
// unfiltered commits
return filteredCommits;
}
// unfiltered commits
return commits;
});
}
|
javascript
|
{
"resource": ""
}
|
q45733
|
randomFileOrFolderName
|
train
|
function randomFileOrFolderName(len = 32) {
if (Number.isFinite(len)) {
return crypto.randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len);
}
throw new Error(`illegal argument: ${len}`);
}
|
javascript
|
{
"resource": ""
}
|
q45734
|
resolveRepositoryPath
|
train
|
function resolveRepositoryPath(options, owner, repo) {
let repPath = path.resolve(options.repoRoot, owner, repo);
if (options.virtualRepos[owner] && options.virtualRepos[owner][repo]) {
repPath = path.resolve(options.virtualRepos[owner][repo].path);
}
return repPath;
}
|
javascript
|
{
"resource": ""
}
|
q45735
|
promiseResult
|
train
|
function promiseResult (options, data) {
log(`promiseResult: data ${data}`);
return new Promise((resolve, reject) => {
/* Check cache to avoid I/O. */
const cacheHit = checkCache(config, pattern);
if (cacheHit !== RESPONSE_UNKNOWN) {
log(`Cache hit: ${cacheHit}`);
return resolve(cacheHit);
}
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let response = '';
res.on('data', (chunk) => {
log(`Got data`);
response += chunk;
});
res.on('end', () => {
log(`end: I got ${JSON.stringify(response)}`);
const result = serverResponseToRESPONSE(response);
log(`end: result ${result}`);
updateCache(config, postObject.pattern, result);
if (result === RESPONSE_INVALID) {
return reject(result);
} else {
return resolve(result);
}
});
});
req.on('error', (e) => {
log(`Error: ${e}`);
return reject(RESPONSE_INVALID);
});
// Write data to request body.
log(`Writing to req:\n${data}`);
req.write(data);
req.end();
});
}
|
javascript
|
{
"resource": ""
}
|
q45736
|
collectionLookup
|
train
|
function collectionLookup (collection, query) {
const id = createID(query.pattern, query.language);
log(`collectionLookup: querying for ${id}`);
return collection.find({_id: id}, {result: 1}).toArray()
.then(
(docs) => {
log(`collectionLookup: Got ${docs.length} docs`);
if (docs.length === 0) {
log(`collectionLookup ${createID(query.pattern, query.language)}: no results`);
return Promise.resolve(PATTERN_UNKNOWN);
} else if (docs.length === 1) {
log(`collectionLookup ${query.pattern}-${query.language}: result: ${docs[0].result}`);
return Promise.resolve(docs[0]);
} else {
log(`collectionLookup unexpected multiple match: ${jsonStringify(docs)}`);
return Promise.resolve(PATTERN_UNKNOWN);
}
},
(e) => {
log(`collectionLookup error: ${e}`);
return Promise.resolve(PATTERN_UNKNOWN);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q45737
|
reportResult
|
train
|
function reportResult (body) {
// Reject invalid reports.
if (!body) {
log(`reportResult: no body`);
return Promise.resolve(PATTERN_INVALID);
}
// Required fields.
let isInvalid = false;
['pattern', 'language', 'result'].forEach((f) => {
if (!body.hasOwnProperty(f) || body[f] === null) {
isInvalid = true;
}
});
if (isInvalid) {
log(`reportResult: invalid: ${jsonStringify(body)}`);
return Promise.resolve(PATTERN_INVALID);
}
// Supported results.
if (body.result === PATTERN_UNKNOWN || body.result === PATTERN_SAFE || body.result === PATTERN_VULNERABLE) {
} else {
log(`reportResult: invalid result ${body.result}`);
return Promise.resolve(PATTERN_INVALID);
}
// Vulnerable must include proof.
if (body.result === PATTERN_VULNERABLE && !body.hasOwnProperty('evilInput')) {
log(`reportResult: ${body.result} but no evilInput`);
return Promise.resolve(PATTERN_INVALID);
}
// Malicious client could spam us with already-solved requests.
// Check if we know the answer already.
return isVulnerable(body)
.then((result) => {
if (result !== PATTERN_UNKNOWN) {
log(`reportResult: already known. Malicious client, or racing clients?`);
return Promise.resolve(result);
}
// New pattern, add to dbUploadCollectionName.
log(`reportResult: new result, updating dbUploadCollectionName`);
return MongoClient.connect(dbUrl)
.then((client) => {
const db = client.db(dbName);
log(`reportResult: connected, now updating DB for {${body.pattern}, ${body.language}} with ${body.result}`);
return collectionUpdate(db.collection(dbUploadCollectionName), {pattern: body.pattern, language: body.language, result: body.result, evilInput: body.evilInput})
.then((result) => {
client.close();
return result;
})
.catch((e) => {
log(`reportResult: db error: ${e}`);
client.close();
return Promise.resolve(PATTERN_UNKNOWN);
});
})
.catch((e) => {
log(`reportResult: db error: ${e}`);
return Promise.resolve(PATTERN_UNKNOWN);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q45738
|
collectionUpdate
|
train
|
function collectionUpdate (collection, result) {
result._id = createID(result.pattern, result.language);
return collection.insertOne(result)
.catch((e) => {
// May fail due to concurrent update on the same value.
log(`collectionUpdate: error: ${e}`);
return Promise.resolve(PATTERN_INVALID);
});
}
|
javascript
|
{
"resource": ""
}
|
q45739
|
runPicturefill
|
train
|
function runPicturefill() {
picturefill();
var intervalId = setInterval( function(){
// When the document has finished loading, stop checking for new images
// https://github.com/ded/domready/blob/master/ready.js#L15
w.picturefill();
if ( /^loaded|^i|^c/.test( doc.readyState ) ) {
clearInterval( intervalId );
return;
}
}, 250 );
if( w.addEventListener ){
var resizeThrottle;
w.addEventListener( "resize", function() {
w.clearTimeout( resizeThrottle );
resizeThrottle = w.setTimeout( function(){
picturefill({ reevaluate: true });
}, 60 );
}, false );
}
}
|
javascript
|
{
"resource": ""
}
|
q45740
|
train
|
function(engine) {
if (typeof GFX_ENGINES[engine] === 'undefined') {
return grunt.fail.warn('Invalid render engine specified');
}
grunt.verbose.ok('Using render engine: ' + GFX_ENGINES[engine].name);
if (engine === 'im') {
return gm.subClass({ imageMagick: (engine === 'im') });
}
return gm;
}
|
javascript
|
{
"resource": ""
}
|
|
q45741
|
train
|
function(properties, options) {
var widthUnit = '',
heightUnit = '';
// name takes precedence
if (properties.name) {
return properties.name;
} else {
// figure out the units for width and height (they can be different)
widthUnit = ((properties.width || 0).toString().indexOf('%') > 0) ? options.units.percentage : options.units.pixel;
heightUnit = ((properties.height || 0 ).toString().indexOf('%') > 0) ? options.units.percentage : options.units.pixel;
if (properties.width && properties.height) {
return parseFloat(properties.width) + widthUnit + options.units.multiply + parseFloat(properties.height) + heightUnit;
} else {
return (properties.width) ? parseFloat(properties.width) + widthUnit : parseFloat(properties.height) + heightUnit;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45742
|
train
|
function(obj, keys, remove) {
var i = 0,
l = keys.length;
for (i = 0; i < l; i++) {
if (obj[keys[i]] && obj[keys[i]].toString().indexOf(remove) > -1) {
obj[keys[i]] = obj[keys[i]].toString().replace(remove, '');
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q45743
|
train
|
function(error, engine) {
if (error.message.indexOf('ENOENT') > -1) {
grunt.log.error(error.message);
grunt.fail.warn('\nPlease ensure ' + GFX_ENGINES[engine].name + ' is installed correctly.\n' +
'`brew install ' + GFX_ENGINES[engine].brewurl + '` or see ' + GFX_ENGINES[engine].url + ' for more details.\n' +
'Alternatively, set options.engine to \'' + GFX_ENGINES[engine].alternative.code + '\' to use ' + GFX_ENGINES[engine].alternative.name + '.\n');
} else {
grunt.fail.warn(error.message);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45744
|
train
|
function(count, name) {
if (count) {
grunt.log.writeln('Resized ' + count.toString().cyan + ' ' +
grunt.util.pluralize(count, 'file/files') + ' for ' + name);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45745
|
train
|
function(srcPath, dstPath, sizeOptions, customDest, origCwd) {
var baseName = '',
dirName = '',
extName = '';
extName = path.extname(dstPath);
baseName = path.basename(dstPath, extName); // filename without extension
if (customDest) {
sizeOptions.path = srcPath.replace(new RegExp(origCwd), "").replace(new RegExp(path.basename(srcPath)+"$"), "");
grunt.template.addDelimiters('size', '{%', '%}');
dirName = grunt.template.process(customDest, {
delimiters: 'size',
data: sizeOptions
});
checkDirectoryExists(path.join(dirName));
return path.join(dirName, baseName + extName);
} else {
dirName = path.dirname(dstPath);
checkDirectoryExists(path.join(dirName));
return path.join(dirName, baseName + sizeOptions.outputName + extName);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45746
|
onMouse
|
train
|
function onMouse(touchType) {
return function(ev) {
// prevent mouse events
if (ev.which !== 1) {
return;
}
// The EventTarget on which the touch point started when it was first placed on the surface,
// even if the touch point has since moved outside the interactive area of that element.
// also, when the target doesnt exist anymore, we update it
if (ev.type === 'mousedown' || !eventTarget || eventTarget && !eventTarget.dispatchEvent) {
eventTarget = ev.target;
}
triggerTouch(touchType, ev);
// reset
if (ev.type === 'mouseup') {
eventTarget = null;
}
};
}
|
javascript
|
{
"resource": ""
}
|
q45747
|
triggerTouch
|
train
|
function triggerTouch(eventName, mouseEv) {
var touchEvent = document.createEvent('Event');
touchEvent.initEvent(eventName, true, true);
touchEvent.altKey = mouseEv.altKey;
touchEvent.ctrlKey = mouseEv.ctrlKey;
touchEvent.metaKey = mouseEv.metaKey;
touchEvent.shiftKey = mouseEv.shiftKey;
touchEvent.touches = getActiveTouches(mouseEv);
touchEvent.targetTouches = getActiveTouches(mouseEv);
touchEvent.changedTouches = createTouchList(mouseEv);
eventTarget.dispatchEvent(touchEvent);
}
|
javascript
|
{
"resource": ""
}
|
q45748
|
start
|
train
|
function start(autoExec) {
debouncedEmit = debounce(emit, 1);
win[ADD_EVENT_LISTENER](POPSTATE, debouncedEmit);
win[ADD_EVENT_LISTENER](HASHCHANGE, debouncedEmit);
doc[ADD_EVENT_LISTENER](clickEvent, click);
if (autoExec) { emit(true); }
}
|
javascript
|
{
"resource": ""
}
|
q45749
|
train
|
function(a, b, retArr) {
if (retArr) {
return [a, b, a + b];
}
return a + b;
}
|
javascript
|
{
"resource": ""
}
|
|
q45750
|
createServer
|
train
|
function createServer() {
function app(req, res, next) {
app.handle(req, res, next);
}
app.method = '*';
merge(app, proto);
merge(app, EventEmitter.prototype);
app.stack = [];
app.params = [];
app._cachedEvents = [] ;
app.routedMethods = {} ;
app.locals = Object.create(null);
for (var i = 0; i < arguments.length; ++i) {
app.use(arguments[i]);
}
//create methods app.invite, app.register, etc..
methods.forEach((method) => {
app[method.toLowerCase()] = app.use.bind(app, method.toLowerCase()) ;
}) ;
//special handling for cdr events
app.on = function(event, listener) {
if (0 === event.indexOf('cdr:')) {
if (app.client) {
app.client.on(event, function() {
var args = Array.prototype.slice.call(arguments) ;
EventEmitter.prototype.emit.apply(app, [event].concat(args)) ;
}) ;
}
else {
this._cachedEvents.push(event) ;
}
}
//delegate all others to standard EventEmitter prototype
return EventEmitter.prototype.addListener.call(app, event, listener) ;
} ;
return app;
}
|
javascript
|
{
"resource": ""
}
|
q45751
|
Callback
|
train
|
function Callback (retType, argTypes, abi, func) {
debug('creating new Callback');
if (typeof abi === 'function') {
func = abi;
abi = undefined;
}
// check args
assert(!!retType, 'expected a return "type" object as the first argument');
assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the second argument');
assert.equal(typeof func, 'function', 'expected a function as the third argument');
// normalize the "types" (they could be strings, so turn into real type
// instances)
retType = ref.coerceType(retType);
argTypes = argTypes.map(ref.coerceType);
// create the `ffi_cif *` instance
const cif = CIF(retType, argTypes, abi);
const argc = argTypes.length;
const callback = _Callback(cif, retType.size, argc, errorReportCallback, (retval, params) => {
debug('Callback function being invoked')
try {
const args = [];
for (var i = 0; i < argc; i++) {
const type = argTypes[i];
const argPtr = params.readPointer(i * ref.sizeof.pointer, type.size);
argPtr.type = type;
args.push(argPtr.deref());
}
// Invoke the user-given function
const result = func.apply(null, args);
try {
ref.set(retval, 0, result, retType);
} catch (e) {
e.message = 'error setting return value - ' + e.message;
throw e;
}
} catch (e) {
return e;
}
});
return callback;
}
|
javascript
|
{
"resource": ""
}
|
q45752
|
variadic_function_generator
|
train
|
function variadic_function_generator () {
debug('variadic_function_generator invoked');
// first get the types of variadic args we are working with
const argTypes = fixedArgTypes.slice();
let key = fixedKey.slice();
for (let i = 0; i < arguments.length; i++) {
const type = ref.coerceType(arguments[i]);
argTypes.push(type);
const ffi_type = Type(type);
assert(ffi_type.name);
key.push(getId(type));
}
// now figure out the return type
const rtnType = ref.coerceType(variadic_function_generator.returnType);
const rtnName = getId(rtnType);
assert(rtnName);
// first let's generate the key and see if we got a cache-hit
key = rtnName + key.join('');
let func = cache[key];
if (func) {
debug('cache hit for key:', key);
} else {
// create the `ffi_cif *` instance
debug('creating the variadic ffi_cif instance for key:', key);
const cif = CIF_var(returnType, argTypes, numFixedArgs, abi);
func = cache[key] = _ForeignFunction(cif, funcPtr, rtnType, argTypes);
}
return func;
}
|
javascript
|
{
"resource": ""
}
|
q45753
|
ForeignFunction
|
train
|
function ForeignFunction (funcPtr, returnType, argTypes, abi) {
debug('creating new ForeignFunction', funcPtr);
// check args
assert(Buffer.isBuffer(funcPtr), 'expected Buffer as first argument');
assert(!!returnType, 'expected a return "type" object as the second argument');
assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the third argument');
// normalize the "types" (they could be strings,
// so turn into real type instances)
returnType = ref.coerceType(returnType);
argTypes = argTypes.map(ref.coerceType);
// create the `ffi_cif *` instance
const cif = CIF(returnType, argTypes, abi);
// create and return the JS proxy function
return _ForeignFunction(cif, funcPtr, returnType, argTypes);
}
|
javascript
|
{
"resource": ""
}
|
q45754
|
train
|
function () {
debug('invoking proxy function');
if (arguments.length !== numArgs) {
throw new TypeError('Expected ' + numArgs +
' arguments, got ' + arguments.length);
}
// storage buffers for input arguments and the return value
const result = Buffer.alloc(resultSize);
const argsList = Buffer.alloc(argsArraySize);
// write arguments to storage areas
let i;
try {
for (i = 0; i < numArgs; i++) {
const argType = argTypes[i];
const val = arguments[i];
const valPtr = ref.alloc(argType, val);
argsList.writePointer(valPtr, i * POINTER_SIZE);
}
} catch (e) {
// counting arguments from 1 is more human readable
i++;
e.message = 'error setting argument ' + i + ' - ' + e.message;
throw e;
}
// invoke the `ffi_call()` function
bindings.ffi_call(cif, funcPtr, result, argsList);
result.type = returnType;
return result.deref();
}
|
javascript
|
{
"resource": ""
}
|
|
q45755
|
Function
|
train
|
function Function (retType, argTypes, abi) {
if (!(this instanceof Function)) {
return new Function(retType, argTypes, abi);
}
debug('creating new FunctionType');
// check args
assert(!!retType, 'expected a return "type" object as the first argument');
assert(Array.isArray(argTypes), 'expected Array of arg "type" objects as the second argument');
// normalize the "types" (they could be strings, so turn into real type
// instances)
this.retType = ref.coerceType(retType);
this.argTypes = argTypes.map(ref.coerceType);
this.abi = null == abi ? bindings.FFI_DEFAULT_ABI : abi;
}
|
javascript
|
{
"resource": ""
}
|
q45756
|
replaceTableNames
|
train
|
function replaceTableNames(sql, identifiers, sequelize) {
const {queryInterface} = sequelize;
_.forIn(identifiers, (model, identifier) => {
const tableName = model.getTableName();
sql = sql.replace(
new RegExp(`\\*${identifier}(?![a-zA-Z0-9_])`, 'g'),
tableName.schema ? tableName.toString() : queryInterface.quoteIdentifier(tableName)
);
});
return sql;
}
|
javascript
|
{
"resource": ""
}
|
q45757
|
addOptions
|
train
|
function addOptions(queryOptions, options) {
const {transaction, logging} = options;
if (transaction !== undefined) queryOptions.transaction = transaction;
if (logging !== undefined) queryOptions.logging = logging;
return queryOptions;
}
|
javascript
|
{
"resource": ""
}
|
q45758
|
inFields
|
train
|
function inFields(fieldName, options) {
const {fields} = options;
if (!fields) return true;
return fields.includes(fieldName);
}
|
javascript
|
{
"resource": ""
}
|
q45759
|
valueFilteredByFields
|
train
|
function valueFilteredByFields(fieldName, item, options) {
if (!inFields(fieldName, options)) return null;
return item.dataValues[fieldName];
}
|
javascript
|
{
"resource": ""
}
|
q45760
|
addToFields
|
train
|
function addToFields(fieldName, options) {
if (inFields(fieldName, options)) return;
options.fields = options.fields.concat([fieldName]);
}
|
javascript
|
{
"resource": ""
}
|
q45761
|
guid
|
train
|
function guid(moduleId) {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return moduleId + '@' + (S4()+S4());
}
|
javascript
|
{
"resource": ""
}
|
q45762
|
w3cTouchConvert
|
train
|
function w3cTouchConvert(touchList) {
var canvasOffset = display._getCanvasOffset();
var tList = [];
for (var i = 0; i < touchList.length; i++) {
var touchEvent = touchList.item(i);
tList.push({
identifier: touchEvent.identifier,
pos: [touchEvent.clientX - canvasOffset[0], touchEvent.clientY - canvasOffset[1]]
});
}
return tList;
}
|
javascript
|
{
"resource": ""
}
|
q45763
|
train
|
function(dimensions) {
var simplex = new gamejs.math.noise.Simplex(Math);
var surfaceData = [];
for (var i=0;i<dimensions[0];i++) {
surfaceData[i] = [];
for (var j=0;j<dimensions[1];j++) {
var val = simplex.get(i/50, j/50) * 255;
surfaceData[i][j] = val;
}
}
return surfaceData;
}
|
javascript
|
{
"resource": ""
}
|
|
q45764
|
colorForTouch
|
train
|
function colorForTouch(touch) {
var id = touch.identifier + (100 * Math.random());
var r = Math.floor(id % 16);
var g = Math.floor(id / 3) % 16;
var b = Math.floor(id / 7) % 16;
r = r.toString(16);
g = g.toString(16);
b = b.toString(16);
var color = "#" + r + g + b;
gamejs.logging.log(color)
return color;
}
|
javascript
|
{
"resource": ""
}
|
q45765
|
train
|
function(actual, expected, maxDifference, message) {
var passes = (actual === expected) || Math.abs(actual - expected) <= maxDifference;
QUnit.push(passes, actual, expected, message);
}
|
javascript
|
{
"resource": ""
}
|
|
q45766
|
train
|
function(actual, expected, minDifference, message) {
var passes = Math.abs(actual - expected) > minDifference;
ok(passes);
QUnit.push(passes, actual, expected, message);
}
|
javascript
|
{
"resource": ""
}
|
|
q45767
|
Ball
|
train
|
function Ball(center) {
this.center = center;
this.growPerSec = Ball.GROW_PER_SEC;
this.radius = this.growPerSec * 2;
this.color = 0;
return this;
}
|
javascript
|
{
"resource": ""
}
|
q45768
|
train
|
function(event) {
var wrapper = getCanvas();
wrapper.requestFullScreen = wrapper.requestFullScreen || wrapper.mozRequestFullScreen || wrapper.webkitRequestFullScreen;
if (!wrapper.requestFullScreen) {
return false;
}
// @xbrowser chrome allows keboard input onl if ask for it (why oh why?)
if (Element.ALLOW_KEYBOARD_INPUT) {
wrapper.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
} else {
wrapper.requestFullScreen();
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q45769
|
train
|
function (name, func, context, a, b, c, d, e, f) {
invokeGuardedCallback$1.apply(ReactErrorUtils, arguments);
}
|
javascript
|
{
"resource": ""
}
|
|
q45770
|
accumulateTwoPhaseDispatchesSingleSkipTarget
|
train
|
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
var targetInst = event._targetInst;
var parentInst = targetInst ? getParentInstance(targetInst) : null;
traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
}
}
|
javascript
|
{
"resource": ""
}
|
q45771
|
getPooledWarningPropertyDefinition
|
train
|
function getPooledWarningPropertyDefinition(propName, getVal) {
var isFunction = typeof getVal === 'function';
return {
configurable: true,
set: set,
get: get
};
function set(val) {
var action = isFunction ? 'setting the method' : 'setting the property';
warn(action, 'This is effectively a no-op');
return val;
}
function get() {
var action = isFunction ? 'accessing the method' : 'accessing the property';
var result = isFunction ? 'This is a no-op function' : 'This is set to null';
warn(action, result);
return getVal;
}
function warn(action, result) {
var warningCondition = false;
warning(warningCondition, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result);
}
}
|
javascript
|
{
"resource": ""
}
|
q45772
|
isEventSupported
|
train
|
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = eventName in document;
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
return isSupported;
}
|
javascript
|
{
"resource": ""
}
|
q45773
|
train
|
function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var win = void 0;
if (nativeEventTarget.window === nativeEventTarget) {
// `nativeEventTarget` is probably a window object.
win = nativeEventTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from = void 0;
var to = void 0;
if (topLevelType === 'topMouseOut') {
from = targetInst;
var related = nativeEvent.relatedTarget || nativeEvent.toElement;
to = related ? getClosestInstanceFromNode(related) : null;
} else {
// Moving to a node from outside the window.
from = null;
to = targetInst;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromNode = from == null ? win : getNodeFromInstance$1(from);
var toNode = to == null ? win : getNodeFromInstance$1(to);
var leave = SyntheticMouseEvent.getPooled(eventTypes$2.mouseLeave, from, nativeEvent, nativeEventTarget);
leave.type = 'mouseleave';
leave.target = fromNode;
leave.relatedTarget = toNode;
var enter = SyntheticMouseEvent.getPooled(eventTypes$2.mouseEnter, to, nativeEvent, nativeEventTarget);
enter.type = 'mouseenter';
enter.target = toNode;
enter.relatedTarget = fromNode;
accumulateEnterLeaveDispatches(leave, enter, from, to);
return [leave, enter];
}
|
javascript
|
{
"resource": ""
}
|
|
q45774
|
trapBubbledEvent
|
train
|
function trapBubbledEvent(topLevelType, handlerBaseName, element) {
if (!element) {
return null;
}
var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;
addEventBubbleListener(element, handlerBaseName,
// Check if interactive and wrap in interactiveUpdates
dispatch.bind(null, topLevelType));
}
|
javascript
|
{
"resource": ""
}
|
q45775
|
trapCapturedEvent
|
train
|
function trapCapturedEvent(topLevelType, handlerBaseName, element) {
if (!element) {
return null;
}
var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;
addEventCaptureListener(element, handlerBaseName,
// Check if interactive and wrap in interactiveUpdates
dispatch.bind(null, topLevelType));
}
|
javascript
|
{
"resource": ""
}
|
q45776
|
computeUniqueAsyncExpiration
|
train
|
function computeUniqueAsyncExpiration() {
var currentTime = recalculateCurrentTime();
var result = computeAsyncExpiration(currentTime);
if (result <= lastUniqueAsyncExpiration) {
// Since we assume the current time monotonically increases, we only hit
// this branch when computeUniqueAsyncExpiration is fired multiple times
// within a 200ms window (or whatever the async bucket size is).
result = lastUniqueAsyncExpiration + 1;
}
lastUniqueAsyncExpiration = result;
return lastUniqueAsyncExpiration;
}
|
javascript
|
{
"resource": ""
}
|
q45777
|
train
|
function (config) {
var getPublicInstance = config.getPublicInstance;
var _ReactFiberScheduler = ReactFiberScheduler(config),
computeUniqueAsyncExpiration = _ReactFiberScheduler.computeUniqueAsyncExpiration,
recalculateCurrentTime = _ReactFiberScheduler.recalculateCurrentTime,
computeExpirationForFiber = _ReactFiberScheduler.computeExpirationForFiber,
scheduleWork = _ReactFiberScheduler.scheduleWork,
requestWork = _ReactFiberScheduler.requestWork,
flushRoot = _ReactFiberScheduler.flushRoot,
batchedUpdates = _ReactFiberScheduler.batchedUpdates,
unbatchedUpdates = _ReactFiberScheduler.unbatchedUpdates,
flushSync = _ReactFiberScheduler.flushSync,
flushControlled = _ReactFiberScheduler.flushControlled,
deferredUpdates = _ReactFiberScheduler.deferredUpdates,
syncUpdates = _ReactFiberScheduler.syncUpdates,
interactiveUpdates = _ReactFiberScheduler.interactiveUpdates,
flushInteractiveUpdates = _ReactFiberScheduler.flushInteractiveUpdates,
legacyContext = _ReactFiberScheduler.legacyContext;
var findCurrentUnmaskedContext = legacyContext.findCurrentUnmaskedContext,
isContextProvider = legacyContext.isContextProvider,
processChildContext = legacyContext.processChildContext;
function getContextForSubtree(parentComponent) {
if (!parentComponent) {
return emptyObject;
}
var fiber = get(parentComponent);
var parentContext = findCurrentUnmaskedContext(fiber);
return isContextProvider(fiber) ? processChildContext(fiber, parentContext) : parentContext;
}
function scheduleRootUpdate(current, element, currentTime, expirationTime, callback) {
{
if (ReactDebugCurrentFiber.phase === 'render' && ReactDebugCurrentFiber.current !== null && !didWarnAboutNestedUpdates) {
didWarnAboutNestedUpdates = true;
warning(false, 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(ReactDebugCurrentFiber.current) || 'Unknown');
}
}
callback = callback === undefined ? null : callback;
{
warning(callback === null || typeof callback === 'function', 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
}
var update = {
expirationTime: expirationTime,
partialState: { element: element },
callback: callback,
isReplace: false,
isForced: false,
capturedValue: null,
next: null
};
insertUpdateIntoFiber(current, update);
scheduleWork(current, expirationTime);
return expirationTime;
}
function updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback) {
// TODO: If this is a nested container, this won't be the root.
var current = container.current;
{
if (ReactFiberInstrumentation_1.debugTool) {
if (current.alternate === null) {
ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
} else if (element === null) {
ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
} else {
ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
}
}
}
var context = getContextForSubtree(parentComponent);
if (container.context === null) {
container.context = context;
} else {
container.pendingContext = context;
}
return scheduleRootUpdate(current, element, currentTime, expirationTime, callback);
}
function findHostInstance(fiber) {
var hostFiber = findCurrentHostFiber(fiber);
if (hostFiber === null) {
return null;
}
return hostFiber.stateNode;
}
return {
createContainer: function (containerInfo, isAsync, hydrate) {
return createFiberRoot(containerInfo, isAsync, hydrate);
},
updateContainer: function (element, container, parentComponent, callback) {
var current = container.current;
var currentTime = recalculateCurrentTime();
var expirationTime = computeExpirationForFiber(current);
return updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback);
},
updateContainerAtExpirationTime: function (element, container, parentComponent, expirationTime, callback) {
var currentTime = recalculateCurrentTime();
return updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback);
},
flushRoot: flushRoot,
requestWork: requestWork,
computeUniqueAsyncExpiration: computeUniqueAsyncExpiration,
batchedUpdates: batchedUpdates,
unbatchedUpdates: unbatchedUpdates,
deferredUpdates: deferredUpdates,
syncUpdates: syncUpdates,
interactiveUpdates: interactiveUpdates,
flushInteractiveUpdates: flushInteractiveUpdates,
flushControlled: flushControlled,
flushSync: flushSync,
getPublicRootInstance: function (container) {
var containerFiber = container.current;
if (!containerFiber.child) {
return null;
}
switch (containerFiber.child.tag) {
case HostComponent:
return getPublicInstance(containerFiber.child.stateNode);
default:
return containerFiber.child.stateNode;
}
},
findHostInstance: findHostInstance,
findHostInstanceWithNoPortals: function (fiber) {
var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
if (hostFiber === null) {
return null;
}
return hostFiber.stateNode;
},
injectIntoDevTools: function (devToolsConfig) {
var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
return injectInternals(_assign({}, devToolsConfig, {
findHostInstanceByFiber: function (fiber) {
return findHostInstance(fiber);
},
findFiberByHostInstance: function (instance) {
if (!findFiberByHostInstance) {
// Might not be implemented by the renderer.
return null;
}
return findFiberByHostInstance(instance);
}
}));
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q45778
|
validateFragmentProps
|
train
|
function validateFragmentProps(fragment) {
currentlyValidatingElement = fragment;
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!VALID_FRAGMENT_PROPS.has(key)) {
warning(false, 'Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.%s', key, getStackAddendum());
break;
}
}
if (fragment.ref !== null) {
warning(false, 'Invalid attribute `ref` supplied to `React.Fragment`.%s', getStackAddendum());
}
currentlyValidatingElement = null;
}
|
javascript
|
{
"resource": ""
}
|
q45779
|
show
|
train
|
function show(options) {
if (!options.message) {
return;
}
prepare_();
let notify = null;
const time = options.time || 8000;
switch (options.type) {
case 'confirm':
notify = draw.confirm(options);
break;
case 'prompt':
notify = draw.prompt(options);
break;
default:
notify = draw.alert(options);
window.setTimeout(function () {
notify.remove();
}, time);
}
wrapper_.appendChild(notify);
notify.classList.add(bounceInClass);
}
|
javascript
|
{
"resource": ""
}
|
q45780
|
init
|
train
|
function init(options) {
setting = options || {};
if (!setting.googleApiKey && !setting.yandexApiKey) {
console.warn(constant.ERROR.MISSING_TOKEN);
return false;
} else if (setting.yandexApiKey) {
serviceType = constant.YANDEX_NAME;
translateSrv = require('./service/yandex.js');
} else {
serviceType = constant.GOOGLE_NAME;
translateSrv = require('./service/google.js');
}
translateSrv.init(setting);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q45781
|
train
|
function (x) {
return (Mexp.math.isDegree ? 180 / Math.PI * Math.acos(x) : Math.acos(x))
}
|
javascript
|
{
"resource": ""
}
|
|
q45782
|
StorageHandle
|
train
|
function StorageHandle() {
this.storageSupport = storageSupportAnalyse();
switch (this.storageSupport) {
case 0:
var exec = require('cordova/exec');
this.storageHandlerDelegate = exec;
break;
case 1:
var localStorageHandle = require('./LocalStorageHandle');
this.storageHandlerDelegate = localStorageHandle;
break;
case 2:
console.log("ALERT! localstorage isn't supported");
break;
default:
console.log("StorageSupport Error");
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q45783
|
getFuzzyLocalTimeFromPoint
|
train
|
function getFuzzyLocalTimeFromPoint(timestamp, point) {
var tile = tilebelt.pointToTile(point[0], point[1], z).join('/');
var locale = tiles[tile];
if (locale) return moment.tz(new Date(timestamp), locale);
else return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q45784
|
getFuzzyTimezoneFromTile
|
train
|
function getFuzzyTimezoneFromTile(tile) {
if (tile[2] === z) {
var key = tile.join('/');
if (key in tiles) return tiles[key];
else throw new Error('tile not found');
} else if (tile[2] > z) {
// higher zoom level (9, 10, 11, ...)
key = _getParent(tile).join('/');
if (key in tiles) return tiles[key];
else throw new Error('tile not found');
} else {
// lower zoom level (..., 5, 6, 7)
var children = _getChildren(tile);
var votes = []; // list of timezone abbrevations
var abbrs = {}; // abbrevation to full name lookup table
children.forEach(function(child) {
key = child.join('/');
if (key in tiles) {
var tz = tiles[key]; // timezone name
// Need to use timezone abbreviation becuase e.g. America/Los_Angeles
// and America/Vancouver are the same. Use a time to determine the
// abbreviation, in case two similar tz have slightly different
// daylight savings schedule.
var abbr = moment.tz(Date.now(), tz)._z.abbrs[0];
votes.push(abbr);
abbrs[abbr] = tz;
}
});
if (votes.length > 1) return abbrs[ss.mode(votes)];
else throw new Error('tile not found');
}
}
|
javascript
|
{
"resource": ""
}
|
q45785
|
isReadableStream
|
train
|
function isReadableStream (stream) {
return stream !== null
&& typeof (stream) === 'object'
&& typeof (stream.pipe) === 'function'
&& typeof (stream._read) === 'function'
&& typeof (stream._readableState) === 'object'
&& stream.readable !== false
}
|
javascript
|
{
"resource": ""
}
|
q45786
|
wait
|
train
|
function wait() {
var isDone = false;
var start = new Date().getTime();
var interval = setInterval(() => {
var now = new Date().getTime();
if ((now - start) >= _retryInterval){
clearInterval(interval);
isDone = true;
}
}, 50);
deasync.loopWhile(() => !isDone);
}
|
javascript
|
{
"resource": ""
}
|
q45787
|
train
|
function(elms, clickParent) {
var elm = elms && elms.length > 0 ? elms[0] : null;
if (!elm) {
return;
}
/*global document*/
var clck_ev = document.createEvent('MouseEvent');
clck_ev.initEvent('click', true, true);
if (clickParent) {
elm.parentElement.dispatchEvent(clck_ev);
} else {
elm.dispatchEvent(clck_ev);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45788
|
convertRequest
|
train
|
function convertRequest(request, functionName, config) {
var url = '';
var result;
if (!request.url) {
if (!request._unboundRequest && !request.collection) {
ErrorHelper.parameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection");
}
if (request.collection) {
ErrorHelper.stringParameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection");
url = request.collection;
//add alternate key feature
if (request.key) {
request.key = ErrorHelper.keyParameterCheck(request.key, 'DynamicsWebApi.' + functionName, "request.key");
}
else if (request.id) {
request.key = ErrorHelper.guidParameterCheck(request.id, 'DynamicsWebApi.' + functionName, "request.id");
}
if (request.key) {
url += "(" + request.key + ")";
}
}
if (request._additionalUrl) {
if (url) {
url += '/';
}
url += request._additionalUrl;
}
result = convertRequestOptions(request, functionName, url, '&', config);
if (request.fetchXml) {
ErrorHelper.stringParameterCheck(request.fetchXml, 'DynamicsWebApi.' + functionName, "request.fetchXml");
result.url += "?fetchXml=" + encodeURIComponent(request.fetchXml);
}
else
if (result.query) {
result.url += "?" + result.query;
}
}
else {
ErrorHelper.stringParameterCheck(request.url, 'DynamicsWebApi.' + functionName, "request.url");
url = request.url.replace(config.webApiUrl, '');
result = convertRequestOptions(request, functionName, url, '&', config);
}
if (request.hasOwnProperty('async') && request.async != null) {
ErrorHelper.boolParameterCheck(request.async, 'DynamicsWebApi.' + functionName, "request.async");
result.async = request.async;
}
else {
result.async = true;
}
return { url: result.url, headers: result.headers, async: result.async };
}
|
javascript
|
{
"resource": ""
}
|
q45789
|
findCollectionName
|
train
|
function findCollectionName(entityName) {
var xrmInternal = Utility.getXrmInternal();
if (!Utility.isNull(xrmInternal)) {
return xrmInternal.getEntitySetName(entityName) || entityName;
}
var collectionName = null;
if (!Utility.isNull(_entityNames)) {
collectionName = _entityNames[entityName];
if (Utility.isNull(collectionName)) {
for (var key in _entityNames) {
if (_entityNames[key] == entityName) {
return entityName;
}
}
}
}
return collectionName;
}
|
javascript
|
{
"resource": ""
}
|
q45790
|
sendRequest
|
train
|
function sendRequest(method, path, config, data, additionalHeaders, responseParams, successCallback, errorCallback, isBatch, isAsync) {
additionalHeaders = additionalHeaders || {};
responseParams = responseParams || {};
//add response parameters to parse
responseParseParams.push(responseParams);
//stringify passed data
var stringifiedData = stringifyData(data, config);
if (isBatch) {
batchRequestCollection.push({
method: method, path: path, config: config, data: stringifiedData, headers: additionalHeaders
});
return;
}
if (path === '$batch') {
var batchResult = BatchConverter.convertToBatch(batchRequestCollection);
stringifiedData = batchResult.body;
//clear an array of requests
batchRequestCollection.length = 0;
additionalHeaders = setStandardHeaders(additionalHeaders);
additionalHeaders['Content-Type'] = 'multipart/mixed;boundary=' + batchResult.boundary;
}
else {
additionalHeaders = setStandardHeaders(additionalHeaders);
}
responseParams.convertedToBatch = false;
//if the URL contains more characters than max possible limit, convert the request to a batch request
if (path.length > 2000) {
var batchBoundary = 'dwa_batch_' + Utility.generateUUID();
var batchBody = [];
batchBody.push('--' + batchBoundary);
batchBody.push('Content-Type: application/http');
batchBody.push('Content-Transfer-Encoding: binary\n');
batchBody.push(method + ' ' + config.webApiUrl + path + ' HTTP/1.1');
for (var key in additionalHeaders) {
if (key === 'Authorization')
continue;
batchBody.push(key + ': ' + additionalHeaders[key]);
//authorization header is an exception. bug #27
delete additionalHeaders[key];
}
batchBody.push('\n--' + batchBoundary + '--');
stringifiedData = batchBody.join('\n');
additionalHeaders = setStandardHeaders(additionalHeaders);
additionalHeaders['Content-Type'] = 'multipart/mixed;boundary=' + batchBoundary;
path = '$batch';
method = 'POST';
responseParams.convertedToBatch = true;
}
if (config.impersonate && !additionalHeaders['MSCRMCallerID']) {
additionalHeaders['MSCRMCallerID'] = config.impersonate;
}
var executeRequest;
/* develblock:start */
if (typeof XMLHttpRequest !== 'undefined') {
/* develblock:end */
executeRequest = require('./xhr');
/* develblock:start */
}
else if (typeof process !== 'undefined') {
executeRequest = require('./http');
}
/* develblock:end */
var sendInternalRequest = function (token) {
if (token) {
if (!additionalHeaders) {
additionalHeaders = {};
}
additionalHeaders['Authorization'] = 'Bearer ' +
(token.hasOwnProperty('accessToken') ?
token.accessToken :
token);
}
executeRequest({
method: method,
uri: config.webApiUrl + path,
data: stringifiedData,
additionalHeaders: additionalHeaders,
responseParams: responseParseParams,
successCallback: successCallback,
errorCallback: errorCallback,
isAsync: isAsync,
timeout: config.timeout
});
};
//call a token refresh callback only if it is set and there is no "Authorization" header set yet
if (config.onTokenRefresh && (!additionalHeaders || (additionalHeaders && !additionalHeaders['Authorization']))) {
config.onTokenRefresh(sendInternalRequest);
}
else {
sendInternalRequest();
}
}
|
javascript
|
{
"resource": ""
}
|
q45791
|
getSerializedType
|
train
|
function getSerializedType(value, descriptor) {
if (value instanceof SerializedVariable) {
return 'SerializedVariable';
} else
if (descriptor) {
return descriptor.type;
} else
if (value instanceof Date) {
return 'Date';
} else
if (typeof value === 'object') {
return 'Json';
} else
if (typeof value === 'boolean') {
return 'Boolean';
} else
if (typeof value === 'number') {
return 'Double';
} else {
return 'String';
}
}
|
javascript
|
{
"resource": ""
}
|
q45792
|
createAuth
|
train
|
function createAuth(type, token) {
if (!type) {
throw new Error('<type> required');
}
if (!token) {
throw new Error('<token> required');
}
/**
* Actual middleware that appends a `Authorization: "${type} ${token}"`
* header to the request options.
*/
return function(worker) {
const workerOptions = worker.options;
const requestOptions = workerOptions.requestOptions || {};
const headers = requestOptions.headers || {};
worker.options = {
...workerOptions,
requestOptions: {
...requestOptions,
headers: {
...headers,
Authorization: `${type} ${token}`
}
}
};
};
}
|
javascript
|
{
"resource": ""
}
|
q45793
|
Worker
|
train
|
function Worker(baseUrl, opts = {}) {
if (!(this instanceof Worker)) {
return new Worker(baseUrl, opts);
}
// inheritance
Emitter.call(this);
this.options = extend({
workerId: uuid.v4()
}, defaultOptions, opts);
this.subscriptions = {};
this.state = STATE_NEW;
// apply extensions
if (this.options.use) {
this.extend(this.options.use);
}
// local variables
this.engineApi = new EngineApi(
baseUrl,
this.options.requestOptions,
this.options.apiVersion
);
if (this.options.pollingDelay) {
throw new Error('options.pollingDelay got replaced with options.autoPoll');
}
// start
if (this.options.autoPoll) {
this.start();
}
}
|
javascript
|
{
"resource": ""
}
|
q45794
|
createBasicAuth
|
train
|
function createBasicAuth(username, password) {
if (!username) {
throw new Error('<username> required');
}
if (typeof password === 'undefined') {
throw new Error('<password> required');
}
const token = base64encode(`${username}:${password}`);
return auth('Basic', token);
}
|
javascript
|
{
"resource": ""
}
|
q45795
|
Logger
|
train
|
function Logger(worker) {
forEach([
'start',
'stop',
'reschedule',
'error',
'poll',
'poll:done',
'poll:error',
'fetchTasks',
'fetchTasks:failed',
'fetchTasks:success',
'worker:register',
'worker:remove',
'executeTask',
'executeTask:complete',
'executeTask:complete:sent',
'executeTask:failed',
'executeTask:failed:sent',
'executeTask:done',
'executeTask:skip',
'executeTasks',
'executeTasks:done',
'extendLock',
'extendLock:success',
'extendLock:failed',
], function(event) {
worker.on(event, function(...args) {
debug(event, ...args);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q45796
|
Metric
|
train
|
function Metric(worker) {
var tasksExecutedCount = 0;
var pollCount = 0;
var executionTime = 0;
var pollTime = 0;
var idleTime = 0;
var activeTasks = 0;
worker.on('executeTask', function() {
activeTasks++;
});
worker.on('executeTask:done', function(task, durationMs) {
tasksExecutedCount++;
activeTasks--;
executionTime += durationMs;
});
worker.on('poll', function() {
pollCount++;
});
worker.on('poll:done', function(reason, durationMs) {
pollTime += durationMs;
});
worker.on('reschedule', function(waitMs) {
idleTime += waitMs;
});
function printStats() {
debug('stats', {
executionTime,
pollTime,
idleTime,
pollCount,
tasksExecutedCount,
activeTasks
});
executionTime = 0;
pollTime = 0;
idleTime = 0;
pollCount = 0;
tasksExecutedCount = 0;
}
var timer;
worker.on('start', () => {
printStats();
timer = setInterval(printStats, 5000);
});
worker.on('stop', () => {
if (timer) {
clearInterval(timer);
}
timer = null;
});
}
|
javascript
|
{
"resource": ""
}
|
q45797
|
Capture
|
train
|
function Capture (deviceIndex, displayMode, pixelFormat) {
this.deviceIndex = deviceIndex;
this.displayMode = displayMode;
this.pixelFormat = pixelFormat;
this.emergencyBrake = null;
if (arguments.length !== 3 || typeof deviceIndex !== 'number' ||
typeof displayMode !== 'number' || typeof pixelFormat !== 'number' ) {
this.emit('error', new Error('Capture requires three number arguments: ' +
'device index, display mode and pixel format'));
} else {
this.capture = macadamNative.capture({
deviceIndex: deviceIndex,
displayMode: displayMode,
pixelFormat: pixelFormat
});//.catch(err => { this.emit('error', err); });
this.capture.then(x => { this.emergencyBrake = x; });
this.running = true;
/* process.on('exit', function () {
console.log('Exiting node.');
if (this.emergencyBrake) this.emergencyBrake.stop();
this.emergencyBrake = null;
process.exit(0);
}); */
process.on('SIGINT', () => {
console.log('Received SIGINT.');
if (this.emergencyBrake) this.emergencyBrake.stop();
this.emergencyBrake = null;
this.running = false;
process.exit();
});
EventEmitter.call(this);
}
}
|
javascript
|
{
"resource": ""
}
|
q45798
|
Playback
|
train
|
function Playback (deviceIndex, displayMode, pixelFormat) {
this.index = 0;
this.deviceIndex = deviceIndex;
this.displayMode = displayMode;
this.pixelFormat = pixelFormat;
this.running = true;
this.emergencyBrake = null;
if (arguments.length !== 3 || typeof deviceIndex !== 'number' ||
typeof displayMode !== 'number' || typeof pixelFormat !== 'number' ) {
this.emit('error', new Error('Playback requires three number arguments: ' +
'index, display mode and pixel format'));
} else {
this.playback = macadamNative.playback({
deviceIndex: deviceIndex,
displayMode: displayMode,
pixelFormat: pixelFormat
}).catch(err => { this.emit('error', err); });
/* process.on('exit', function () {
console.log('Exiting node.');
if (this.emergencyBrake) this.emergencyBrake.stop();
this.running = false;
process.exit(0);
}); */
process.on('SIGINT', () => {
console.log('Received SIGINT.');
if (this.emergencyBrake) this.emergencyBrake.stop();
this.running = false;
process.exit();
});
}
EventEmitter.call(this);
}
|
javascript
|
{
"resource": ""
}
|
q45799
|
parseJSON
|
train
|
function parseJSON(cmd) {
try {
var json = JSON.parse(cmd.rest);
} catch (e) {
return false;
}
// Ensure it's an array.
if (!Array.isArray(json)) {
return false;
}
// Ensure every entry in the array is a string.
if (!json.every(function (entry) {
return typeof(entry) === 'string';
})) {
return false;
}
cmd.args = json;
return true;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.