_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q27600 | serializeUserData | train | function serializeUserData(object) {
try {
return JSON.parse(JSON.stringify(object.userData));
} catch (error) {
console.warn(
"THREE.GLTFExporter: userData of '" +
object.name +
"' " +
"won't be serialized because of JSON.stringify error - " +
error.message
);
return {};
}
} | javascript | {
"resource": ""
} |
q27601 | processBuffer | train | function processBuffer(buffer) {
if (!outputJSON.buffers) {
outputJSON.buffers = [{ byteLength: 0 }];
}
// All buffers are merged before export.
buffers.push(buffer);
return 0;
} | javascript | {
"resource": ""
} |
q27602 | processBufferView | train | function processBufferView(attribute, componentType, start, count, target) {
if (!outputJSON.bufferViews) {
outputJSON.bufferViews = [];
}
// Create a new dataview and dump the attribute's array into it
var componentSize;
if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) {
componentSize = 1;
} else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) {
componentSize = 2;
} else {
componentSize = 4;
}
var byteLength = getPaddedBufferSize(
count * attribute.itemSize * componentSize
);
var dataView = new DataView(new ArrayBuffer(byteLength));
var offset = 0;
for (var i = start; i < start + count; i++) {
for (var a = 0; a < attribute.itemSize; a++) {
// @TODO Fails on InterleavedBufferAttribute, and could probably be
// optimized for normal BufferAttribute.
var value = attribute.array[i * attribute.itemSize + a];
if (componentType === WEBGL_CONSTANTS.FLOAT) {
dataView.setFloat32(offset, value, true);
} else if (componentType === WEBGL_CONSTANTS.UNSIGNED_INT) {
dataView.setUint32(offset, value, true);
} else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) {
dataView.setUint16(offset, value, true);
} else if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) {
dataView.setUint8(offset, value);
}
offset += componentSize;
}
}
var gltfBufferView = {
buffer: processBuffer(dataView.buffer),
byteOffset: byteOffset,
byteLength: byteLength
};
if (target !== undefined) gltfBufferView.target = target;
if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) {
// Only define byteStride for vertex attributes.
gltfBufferView.byteStride = attribute.itemSize * componentSize;
}
byteOffset += byteLength;
outputJSON.bufferViews.push(gltfBufferView);
// @TODO Merge bufferViews where possible.
var output = {
id: outputJSON.bufferViews.length - 1,
byteLength: 0
};
return output;
} | javascript | {
"resource": ""
} |
q27603 | processBufferViewImage | train | function processBufferViewImage(blob) {
if (!outputJSON.bufferViews) {
outputJSON.bufferViews = [];
}
return new Promise(function(resolve) {
var reader = new window.FileReader();
reader.readAsArrayBuffer(blob);
reader.onloadend = function() {
var buffer = getPaddedArrayBuffer(reader.result);
var bufferView = {
buffer: processBuffer(buffer),
byteOffset: byteOffset,
byteLength: buffer.byteLength
};
byteOffset += buffer.byteLength;
outputJSON.bufferViews.push(bufferView);
resolve(outputJSON.bufferViews.length - 1);
};
});
} | javascript | {
"resource": ""
} |
q27604 | processAccessor | train | function processAccessor(attribute, geometry, start, count) {
var types = {
1: 'SCALAR',
2: 'VEC2',
3: 'VEC3',
4: 'VEC4',
16: 'MAT4'
};
var componentType;
// Detect the component type of the attribute array (float, uint or ushort)
if (attribute.array.constructor === Float32Array) {
componentType = WEBGL_CONSTANTS.FLOAT;
} else if (attribute.array.constructor === Uint32Array) {
componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
} else if (attribute.array.constructor === Uint16Array) {
componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
} else if (attribute.array.constructor === Uint8Array) {
componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
} else {
throw new Error(
'THREE.GLTFExporter: Unsupported bufferAttribute component type.'
);
}
if (start === undefined) start = 0;
if (count === undefined) count = attribute.count;
// @TODO Indexed buffer geometry with drawRange not supported yet
if (
options.truncateDrawRange &&
geometry !== undefined &&
geometry.index === null
) {
var end = start + count;
var end2 =
geometry.drawRange.count === Infinity
? attribute.count
: geometry.drawRange.start + geometry.drawRange.count;
start = Math.max(start, geometry.drawRange.start);
count = Math.min(end, end2) - start;
if (count < 0) count = 0;
}
// Skip creating an accessor if the attribute doesn't have data to export
if (count === 0) {
return null;
}
var minMax = getMinMax(attribute, start, count);
var bufferViewTarget;
// If geometry isn't provided, don't infer the target usage of the bufferView. For
// animation samplers, target must not be set.
if (geometry !== undefined) {
bufferViewTarget =
attribute === geometry.index
? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER
: WEBGL_CONSTANTS.ARRAY_BUFFER;
}
var bufferView = processBufferView(
attribute,
componentType,
start,
count,
bufferViewTarget
);
var gltfAccessor = {
bufferView: bufferView.id,
byteOffset: bufferView.byteOffset,
componentType: componentType,
count: count,
max: minMax.max,
min: minMax.min,
type: types[attribute.itemSize]
};
if (!outputJSON.accessors) {
outputJSON.accessors = [];
}
outputJSON.accessors.push(gltfAccessor);
return outputJSON.accessors.length - 1;
} | javascript | {
"resource": ""
} |
q27605 | processAnimation | train | function processAnimation(clip, root) {
if (!outputJSON.animations) {
outputJSON.animations = [];
}
var channels = [];
var samplers = [];
for (var i = 0; i < clip.tracks.length; ++i) {
var track = clip.tracks[i];
var trackBinding = THREE.PropertyBinding.parseTrackName(track.name);
var trackNode = THREE.PropertyBinding.findNode(
root,
trackBinding.nodeName
);
var trackProperty = PATH_PROPERTIES[trackBinding.propertyName];
if (trackBinding.objectName === 'bones') {
if (trackNode.isSkinnedMesh === true) {
trackNode = trackNode.skeleton.getBoneByName(
trackBinding.objectIndex
);
} else {
trackNode = undefined;
}
}
if (!trackNode || !trackProperty) {
console.warn(
'THREE.GLTFExporter: Could not export animation track "%s".',
track.name
);
return null;
}
var inputItemSize = 1;
var outputItemSize = track.values.length / track.times.length;
if (trackProperty === PATH_PROPERTIES.morphTargetInfluences) {
if (
trackNode.morphTargetInfluences.length !== 1 &&
trackBinding.propertyIndex !== undefined
) {
console.warn(
'THREE.GLTFExporter: Skipping animation track "%s". ' +
'Morph target keyframe tracks must target all available morph targets ' +
'for the given mesh.',
track.name
);
continue;
}
outputItemSize /= trackNode.morphTargetInfluences.length;
}
var interpolation;
// @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
// Detecting glTF cubic spline interpolant by checking factory method's special property
// GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
// valid value from .getInterpolation().
if (
track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ===
true
) {
interpolation = 'CUBICSPLINE';
// itemSize of CUBICSPLINE keyframe is 9
// (VEC3 * 3: inTangent, splineVertex, and outTangent)
// but needs to be stored as VEC3 so dividing by 3 here.
outputItemSize /= 3;
} else if (track.getInterpolation() === THREE.InterpolateDiscrete) {
interpolation = 'STEP';
} else {
interpolation = 'LINEAR';
}
samplers.push({
input: processAccessor(
new THREE.BufferAttribute(track.times, inputItemSize)
),
output: processAccessor(
new THREE.BufferAttribute(track.values, outputItemSize)
),
interpolation: interpolation
});
channels.push({
sampler: samplers.length - 1,
target: {
node: nodeMap.get(trackNode),
path: trackProperty
}
});
}
outputJSON.animations.push({
name: clip.name || 'clip_' + outputJSON.animations.length,
samplers: samplers,
channels: channels
});
return outputJSON.animations.length - 1;
} | javascript | {
"resource": ""
} |
q27606 | processNode | train | function processNode(object) {
if (object.isLight) {
console.warn(
'GLTFExporter: Unsupported node type:',
object.constructor.name
);
return null;
}
if (!outputJSON.nodes) {
outputJSON.nodes = [];
}
var gltfNode = {};
if (options.trs) {
var rotation = object.quaternion.toArray();
var position = object.position.toArray();
var scale = object.scale.toArray();
if (!equalArray(rotation, [0, 0, 0, 1])) {
gltfNode.rotation = rotation;
}
if (!equalArray(position, [0, 0, 0])) {
gltfNode.translation = position;
}
if (!equalArray(scale, [1, 1, 1])) {
gltfNode.scale = scale;
}
} else {
object.updateMatrix();
if (
!equalArray(object.matrix.elements, [
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
])
) {
gltfNode.matrix = object.matrix.elements;
}
}
// We don't export empty strings name because it represents no-name in Three.js.
if (object.name !== '') {
gltfNode.name = String(object.name);
}
if (object.userData && Object.keys(object.userData).length > 0) {
gltfNode.extras = serializeUserData(object);
}
if (object.isMesh || object.isLine || object.isPoints) {
var mesh = processMesh(object);
if (mesh !== null) {
gltfNode.mesh = mesh;
}
} else if (object.isCamera) {
gltfNode.camera = processCamera(object);
}
if (object.isSkinnedMesh) {
skins.push(object);
}
if (object.children.length > 0) {
var children = [];
for (var i = 0, l = object.children.length; i < l; i++) {
var child = object.children[i];
if (child.visible || options.onlyVisible === false) {
var node = processNode(child);
if (node !== null) {
children.push(node);
}
}
}
if (children.length > 0) {
gltfNode.children = children;
}
}
outputJSON.nodes.push(gltfNode);
var nodeIndex = outputJSON.nodes.length - 1;
nodeMap.set(object, nodeIndex);
return nodeIndex;
} | javascript | {
"resource": ""
} |
q27607 | processObjects | train | function processObjects(objects) {
var scene = new THREE.Scene();
scene.name = 'AuxScene';
for (var i = 0; i < objects.length; i++) {
// We push directly to children instead of calling `add` to prevent
// modify the .parent and break its original scene and hierarchy
scene.children.push(objects[i]);
}
processScene(scene);
} | javascript | {
"resource": ""
} |
q27608 | train | function () {
let scope = context.getScope();
while (scope) {
const node = scope.block && scope.block.parent && scope.block.parent.parent;
if (node && utils.isES5Component(node)) {
return node;
}
scope = scope.upper;
}
return null;
} | javascript | {
"resource": ""
} | |
q27609 | train | function () {
let scope = context.getScope();
while (scope && scope.type !== 'class') {
scope = scope.upper;
}
const node = scope && scope.block;
if (!node || !utils.isES6Component(node)) {
return null;
}
return node;
} | javascript | {
"resource": ""
} | |
q27610 | markVariableAsUsed | train | function markVariableAsUsed(context, name) {
let scope = context.getScope();
let variables;
let i;
let len;
let found = false;
// Special Node.js scope means we need to start one level deeper
if (scope.type === 'global') {
while (scope.childScopes.length) {
scope = scope.childScopes[0];
}
}
do {
variables = scope.variables;
for (i = 0, len = variables.length; i < len; i++) { // eslint-disable-line no-plusplus
if (variables[i].name === name) {
variables[i].eslintUsed = true;
found = true;
}
}
scope = scope.upper;
} while (scope);
return found;
} | javascript | {
"resource": ""
} |
q27611 | findVariable | train | function findVariable(variables, name) {
let i;
let len;
for (i = 0, len = variables.length; i < len; i++) { // eslint-disable-line no-plusplus
if (variables[i].name === name) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q27612 | variablesInScope | train | function variablesInScope(context) {
let scope = context.getScope();
let variables = scope.variables;
while (scope.type !== 'global') {
scope = scope.upper;
variables = scope.variables.concat(variables);
}
if (scope.childScopes.length) {
variables = scope.childScopes[0].variables.concat(variables);
if (scope.childScopes[0].childScopes.length) {
variables = scope.childScopes[0].childScopes[0].variables.concat(variables);
}
}
return variables;
} | javascript | {
"resource": ""
} |
q27613 | getClosestPackage | train | function getClosestPackage(modulePath) {
let root;
let pkg;
// Catch findRoot or require errors
try {
root = findRoot(modulePath);
pkg = require(path.join(root, "package.json"));
} catch (e) {
return null;
}
// If the package.json does not have a name property, try again from
// one level higher.
// https://github.com/jsdnxx/find-root/issues/2
// https://github.com/date-fns/date-fns/issues/264#issuecomment-265128399
if (!pkg.name) {
return getClosestPackage(path.resolve(root, ".."));
}
return {
package: pkg,
path: root
};
} | javascript | {
"resource": ""
} |
q27614 | Row | train | function Row(props) {
const {
rowClass,
columns,
widgets,
onRemove,
layout,
rowIndex,
editable,
frameComponent,
editableColumnClass,
droppableColumnClass,
addWidgetComponentText,
addWidgetComponent,
onAdd,
onMove,
onEdit,
} = props;
const items = columns.map((column, index) => { // eslint-disable-line arrow-body-style
return (
<Column
key={index}
className={column.className}
onAdd={onAdd}
layout={layout}
rowIndex={rowIndex}
columnIndex={index}
editable={editable}
onMove={onMove}
editableColumnClass={editableColumnClass}
droppableColumnClass={droppableColumnClass}
addWidgetComponent={addWidgetComponent}
addWidgetComponentText={addWidgetComponentText}
>
<Widgets
key={index}
widgets={column.widgets}
containerClassName={column.containerClassName}
widgetTypes={widgets}
onRemove={onRemove}
layout={layout}
rowIndex={rowIndex}
columnIndex={index}
editable={editable}
frameComponent={frameComponent}
onMove={onMove}
onEdit={onEdit}
/>
</Column>
);
});
return (
<div className={rowClass}>
{items}
</div>
);
} | javascript | {
"resource": ""
} |
q27615 | waitOn | train | function waitOn(opts, cb) {
if (cb !== undefined) {
return waitOnImpl(opts, cb);
} else {
return new Promise(function (resolve, reject) {
waitOnImpl(opts, function(err) {
if (err) {
reject(err);
} else {
resolve();
}
})
});
}
} | javascript | {
"resource": ""
} |
q27616 | GenerateDefaultValues | train | function GenerateDefaultValues(neode, model, properties) {
const output = GenerateDefaultValuesAsync(neode, model, properties);
return Promise.resolve(output);
} | javascript | {
"resource": ""
} |
q27617 | splitProperties | train | function splitProperties(mode, model, properties) {
var merge_on = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
var inline = {};
var set = {};
var on_create = {};
var on_match = {};
// Calculate Set Properties
model.properties().forEach(function (property) {
var name = property.name();
// Skip if not set
if (!properties.hasOwnProperty(name)) {
return;
}
var value = (0, _Entity.valueToCypher)(property, properties[name]);
// If mode is create, go ahead and set everything
if (mode == 'create') {
inline[name] = value;
} else if (merge_on.indexOf(name) > -1) {
inline[name] = value;
}
// Only set protected properties on creation
else if (property.protected() || property.primary()) {
on_create[name] = value;
}
// Read-only property?
else if (!property.readonly()) {
set[name] = value;
}
});
return {
inline: inline,
on_create: on_create,
on_match: on_match,
set: set
};
} | javascript | {
"resource": ""
} |
q27618 | addRelationshipToStatement | train | function addRelationshipToStatement(neode, builder, alias, rel_alias, target_alias, relationship, value, aliases, mode) {
if (aliases.length > MAX_CREATE_DEPTH) {
return;
}
// Extract Node
var node_alias = relationship.nodeAlias();
var node_value = value[node_alias];
delete value[node_alias];
// Create Node
// If Node is passed, attempt to create a relationship to that specific node
if (node_value instanceof _Node2.default) {
builder.match(target_alias).whereId(target_alias, node_value.identity());
}
// If Primary key is passed then try to match on that
else if (typeof node_value == 'string' || typeof node_value == 'number') {
var model = neode.model(relationship.target());
builder.merge(target_alias, model, _defineProperty({}, model.primaryKey(), node_value));
}
// If Map is passed, attempt to create that node and then relate
else if (Object.keys(node_value).length) {
var _model = neode.model(relationship.target());
node_value = _GenerateDefaultValues2.default.async(neode, _model, node_value);
addNodeToStatement(neode, builder, target_alias, _model, node_value, aliases, mode, _model.mergeFields());
}
// Create the Relationship
builder[mode](alias).relationship(relationship.relationship(), relationship.direction(), rel_alias).to(target_alias);
// Set Relationship Properties
relationship.properties().forEach(function (property) {
var name = property.name();
if (value.hasOwnProperty(name)) {
builder.set(rel_alias + '.' + name, value[name]);
}
});
} | javascript | {
"resource": ""
} |
q27619 | addNodeRelationshipToStatement | train | function addNodeRelationshipToStatement(neode, builder, alias, rel_alias, target_alias, relationship, value, aliases, mode) {
if (aliases.length > MAX_CREATE_DEPTH) {
return;
}
// If Node is passed, attempt to create a relationship to that specific node
if (value instanceof _Node2.default) {
builder.match(target_alias).whereId(target_alias, value.identity());
}
// If Primary key is passed then try to match on that
else if (typeof value == 'string' || typeof value == 'number') {
var model = neode.model(relationship.target());
builder.merge(target_alias, model, _defineProperty({}, model.primaryKey(), value));
}
// If Map is passed, attempt to create that node and then relate
// TODO: What happens when we need to validate this?
// TODO: Is mergeFields() the right option here?
else if (Object.keys(value).length) {
var _model2 = neode.model(relationship.target());
value = _GenerateDefaultValues2.default.async(neode, _model2, value);
addNodeToStatement(neode, builder, target_alias, _model2, value, aliases, mode, _model2.mergeFields());
}
// Create the Relationship
builder[mode](alias).relationship(relationship.relationship(), relationship.direction(), rel_alias).to(target_alias);
} | javascript | {
"resource": ""
} |
q27620 | _valueToJson | train | function _valueToJson(property, value) {
if (_neo4jDriver.v1.isInt(value)) {
return value.toNumber();
} else if (_neo4jDriver.v1.temporal.isDate(value) || _neo4jDriver.v1.temporal.isDateTime(value) || _neo4jDriver.v1.temporal.isTime(value) || _neo4jDriver.v1.temporal.isLocalDateTime(value) || _neo4jDriver.v1.temporal.isLocalTime(value) || _neo4jDriver.v1.temporal.isDuration(value)) {
return value.toString();
} else if (_neo4jDriver.v1.spatial.isPoint(value)) {
switch (value.srid.toString()) {
// SRID values: @https://neo4j.com/docs/developer-manual/current/cypher/functions/spatial/
case '4326':
// WGS 84 2D
return { longitude: value.x, latitude: value.y };
case '4979':
// WGS 84 3D
return { longitude: value.x, latitude: value.y, height: value.z };
case '7203':
// Cartesian 2D
return { x: value.x, y: value.y };
case '9157':
// Cartesian 3D
return { x: value.x, y: value.y, z: value.z };
}
}
return value;
} | javascript | {
"resource": ""
} |
q27621 | CleanValue | train | function CleanValue(config, value) {
// Convert temporal to a native date?
if (temporal.indexOf(config.type.toLowerCase()) > -1 && typeof value == 'number') {
value = new Date(value);
}
// Clean Values
switch (config.type.toLowerCase()) {
case 'float':
value = parseFloat(value);
break;
case 'int':
case 'integer':
value = parseInt(value);
break;
case 'bool':
case 'boolean':
value = !!value;
break;
case 'timestamp':
value = value instanceof Date ? value.getTime() : value;
break;
case 'date':
value = value instanceof Date ? _neo4jDriver.v1.types.Date.fromStandardDate(value) : value;
break;
case 'datetime':
value = value instanceof Date ? _neo4jDriver.v1.types.DateTime.fromStandardDate(value) : value;
break;
case 'localdatetime':
value = value instanceof Date ? _neo4jDriver.v1.types.LocalDateTime.fromStandardDate(value) : value;
break;
case 'time':
value = value instanceof Date ? _neo4jDriver.v1.types.Time.fromStandardDate(value) : value;
break;
case 'localtime':
value = value instanceof Date ? _neo4jDriver.v1.types.LocalTime.fromStandardDate(value) : value;
break;
case 'point':
// SRID values: @https://neo4j.com/docs/developer-manual/current/cypher/functions/spatial/
if (isNaN(value.x)) {
// WGS 84
if (isNaN(value.height)) {
value = new _neo4jDriver.v1.types.Point(4326, // WGS 84 2D
value.longitude, value.latitude);
} else {
value = new _neo4jDriver.v1.types.Point(4979, // WGS 84 3D
value.longitude, value.latitude, value.height);
}
} else {
if (isNaN(value.z)) {
value = new _neo4jDriver.v1.types.Point(7203, // Cartesian 2D
value.x, value.y);
} else {
value = new _neo4jDriver.v1.types.Point(9157, // Cartesian 3D
value.x, value.y, value.z);
}
}
break;
}
return value;
} | javascript | {
"resource": ""
} |
q27622 | addCascadeDeleteNode | train | function addCascadeDeleteNode(neode, builder, from_alias, relationship, aliases, to_depth) {
if ( aliases.length > to_depth ) return;
const rel_alias = from_alias + relationship.name() + '_rel';
const node_alias = from_alias + relationship.name() + '_node';
const target = neode.model( relationship.target() );
// Optional Match
builder.optionalMatch(from_alias)
.relationship(relationship.relationship(), relationship.direction(), rel_alias)
.to(node_alias, relationship.target());
// Check for cascade deletions
target.relationships().forEach(relationship => {
switch ( relationship.cascade() ) {
case 'delete':
addCascadeDeleteNode(neode, builder, node_alias, relationship, aliases.concat(node_alias), to_depth);
break;
// case 'detach':
// addDetachNode(neode, builder, node_alias, relationship, aliases);
// break;
}
});
// Delete it
builder.detachDelete(node_alias);
} | javascript | {
"resource": ""
} |
q27623 | DeleteNode | train | function DeleteNode(neode, identity, model) {
var to_depth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : MAX_EAGER_DEPTH;
var alias = 'this';
var to_delete = [];
var aliases = [alias];
var depth = 1;
var builder = new _Builder2.default(neode).match(alias, model).whereId(alias, identity);
// Cascade delete to relationships
model.relationships().forEach(function (relationship) {
switch (relationship.cascade()) {
case 'delete':
addCascadeDeleteNode(neode, builder, alias, relationship, aliases, to_depth);
break;
// case 'detach':
// addDetachNode(neode, builder, alias, relationship, aliases);
// break;
}
});
// Detach Delete target node
builder.detachDelete(alias);
return builder.execute(_Builder.mode.WRITE);
} | javascript | {
"resource": ""
} |
q27624 | eagerPattern | train | function eagerPattern(neode, depth, alias, rel) {
var builder = new _Builder2.default();
var name = rel.name();
var type = rel.type();
var relationship = rel.relationship();
var direction = rel.direction();
var target = rel.target();
var relationship_variable = alias + '_' + name + '_rel';
var node_variable = alias + '_' + name + '_node';
var target_model = neode.model(target);
// Build Pattern
builder.match(alias).relationship(relationship, direction, relationship_variable).to(node_variable, target_model);
var fields = node_variable;
switch (type) {
case 'node':
case 'nodes':
fields = eagerNode(neode, depth + 1, node_variable, target_model);
break;
case 'relationship':
case 'relationships':
fields = eagerRelationship(neode, depth + 1, relationship_variable, rel.nodeAlias(), node_variable, target_model);
}
var pattern = name + ': [ ' + builder.pattern().trim() + ' | ' + fields + ' ]';
// Get the first?
if (type === 'node' || type === 'relationship') {
return pattern + '[0]';
}
return pattern;
} | javascript | {
"resource": ""
} |
q27625 | eagerNode | train | function eagerNode(neode, depth, alias, model) {
var indent = ' '.repeat(depth * 2);
var pattern = '\n' + indent + ' ' + alias + ' { ';
// Properties
pattern += '\n' + indent + indent + '.*';
// ID
pattern += '\n' + indent + indent + ',' + EAGER_ID + ': id(' + alias + ')';
// Labels
pattern += '\n' + indent + indent + ',' + EAGER_LABELS + ': labels(' + alias + ')';
// Eager
if (model && depth <= MAX_EAGER_DEPTH) {
model.eager().forEach(function (rel) {
pattern += '\n' + indent + indent + ',' + eagerPattern(neode, depth, alias, rel);
});
}
pattern += '\n' + indent + '}';
return pattern;
} | javascript | {
"resource": ""
} |
q27626 | eagerRelationship | train | function eagerRelationship(neode, depth, alias, node_alias, node_variable, node_model) {
var indent = ' '.repeat(depth * 2);
var pattern = '\n' + indent + ' ' + alias + ' { ';
// Properties
pattern += '\n' + indent + indent + '.*';
// ID
pattern += '\n' + indent + indent + ',' + EAGER_ID + ': id(' + alias + ')';
// Type
pattern += '\n' + indent + indent + ',' + EAGER_TYPE + ': type(' + alias + ')';
// Node Alias
// pattern += `\n,${indent}${indent},${node_alias}`
pattern += '\n' + indent + indent + ',' + node_alias + ': ';
pattern += eagerNode(neode, depth + 1, node_variable, node_model);
pattern += '\n' + indent + '}';
return pattern;
} | javascript | {
"resource": ""
} |
q27627 | normalizeUnit | train | function normalizeUnit(unit) {
unit = toStr(unit);
if (unitShorthandMap[unit]) return unitShorthandMap[unit];
return unit.toLowerCase().replace(regEndS, '');
} | javascript | {
"resource": ""
} |
q27628 | isAvailable | train | function isAvailable(port) {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
const options = {};
options.port = port;
server.listen(options, () => {
const { port } = server.address();
server.close(() => {
resolve(port);
});
});
});
} | javascript | {
"resource": ""
} |
q27629 | loadFiles | train | function loadFiles(paths, callbackFn, args) {
// listify paths
paths = paths.push ? paths : [paths];
var numWaiting = paths.length,
x = numWaiting,
pathsNotFound = [],
fn,
i;
// define callback function
fn = function(path, result, defaultPrevented) {
// handle error
if (result == 'e') pathsNotFound.push(path);
// handle beforeload event. If defaultPrevented then that means the load
// will be blocked (ex. Ghostery/ABP on Safari)
if (result == 'b') {
if (defaultPrevented) pathsNotFound.push(path);
else return;
}
numWaiting--;
if (!numWaiting) callbackFn(pathsNotFound);
};
// load scripts
for (i=0; i < x; i++) loadFile(paths[i], fn, args);
} | javascript | {
"resource": ""
} |
q27630 | log | train | function log(msg) {
var d = new Date(), ts;
ts = d.toLocaleTimeString().split(' ');
ts = ts[0] + '.' + d.getMilliseconds() + ' ' + ts[1];
console.log('[' + ts + '] ' + msg);
} | javascript | {
"resource": ""
} |
q27631 | placeholder | train | function placeholder (input, property) {
return ( input === undefined || input === '' || input === null ) ? property : input;
} | javascript | {
"resource": ""
} |
q27632 | capitalize | train | function capitalize (value, options) {
options = options || {}
var onlyFirstLetter = options.onlyFirstLetter != null ? options.onlyFirstLetter : false
if (!value && value !== 0) return ''
if(onlyFirstLetter === true) {
return value.charAt(0).toUpperCase() + value.slice(1)
} else {
value = value.toString().toLowerCase().split(' ')
return value.map(function(item) {
return item.charAt(0).toUpperCase() + item.slice(1)
}).join(' ')
}
} | javascript | {
"resource": ""
} |
q27633 | limitBy | train | function limitBy (arr, n, offset) {
offset = offset ? parseInt(offset, 10) : 0
n = util.toNumber(n)
return typeof n === 'number'
? arr.slice(offset, offset + n)
: arr
} | javascript | {
"resource": ""
} |
q27634 | ordinal | train | function ordinal (value, options) {
options = options || {}
var output = ''
var includeNumber = options.includeNumber != null ? options.includeNumber : false
if(includeNumber === true) output += value
var j = value % 10,
k = value % 100
if (j == 1 && k != 11) output += 'st'
else if (j == 2 && k != 12) output += 'nd'
else if (j == 3 && k != 13) output += 'rd'
else output += 'th'
return output
} | javascript | {
"resource": ""
} |
q27635 | truncate | train | function truncate (value, length) {
length = length || 15
if( !value || typeof value !== 'string' ) return ''
if( value.length <= length) return value
return value.substring(0, length) + '...'
} | javascript | {
"resource": ""
} |
q27636 | find | train | function find(arr, search)
{
var array = filterBy.apply(this, arguments);
array.splice(1);
return array;
} | javascript | {
"resource": ""
} |
q27637 | pluralize | train | function pluralize (value, word, options) {
options = options || {}
var output = ''
var includeNumber = options.includeNumber != null ? options.includeNumber : false
if(includeNumber === true) output += value + ' '
if(!value && value !== 0 || !word) return output
if(Array.isArray(word)) {
output += word[value - 1] || word[word.length - 1]
} else {
output += word + (value === 1 ? '' : 's')
}
return output
} | javascript | {
"resource": ""
} |
q27638 | train | function(name, source) {
var s = source;
var newEvents = s.events;
if (newEvents) {
newEvents.forEach(function(e) {
if (s[e]) {
this.eventMap[e] = s[e].bind(s);
}
}, this);
this.eventSources[name] = s;
this.eventSourceList.push(s);
}
} | javascript | {
"resource": ""
} | |
q27639 | train | function(target, events) {
for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) {
this.addEvent(target, e);
}
} | javascript | {
"resource": ""
} | |
q27640 | train | function(target, events) {
for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) {
this.removeEvent(target, e);
}
} | javascript | {
"resource": ""
} | |
q27641 | train | function(inEvent) {
var t = inEvent._target;
if (t) {
t.dispatchEvent(inEvent);
// clone the event for the gesture system to process
// clone after dispatch to pick up gesture prevention code
var clone = this.cloneEvent(inEvent);
clone.target = t;
this.fillGestureQueue(clone);
}
} | javascript | {
"resource": ""
} | |
q27642 | train | function(inEvent) {
var lts = this.lastTouches;
var x = inEvent.clientX, y = inEvent.clientY;
for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
// simulated mouse events will be swallowed near a primary touchend
var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
return true;
}
}
} | javascript | {
"resource": ""
} | |
q27643 | train | function(touch) {
var dx = Math.abs(x - touch.x), dy = Math.abs(y - touch.y);
return (dx <= DEDUP_DIST && dy <= DEDUP_DIST);
} | javascript | {
"resource": ""
} | |
q27644 | findScope | train | function findScope(model, prop) {
while (model[parentScopeName] &&
!Object.prototype.hasOwnProperty.call(model, prop)) {
model = model[parentScopeName];
}
return model;
} | javascript | {
"resource": ""
} |
q27645 | train | function(value) {
var parts = [];
for (var key in value) {
parts.push(convertStylePropertyName(key) + ': ' + value[key]);
}
return parts.join('; ');
} | javascript | {
"resource": ""
} | |
q27646 | train | function(template) {
var indexIdent = template.polymerExpressionIndexIdent_;
if (!indexIdent)
return;
return function(templateInstance, index) {
templateInstance.model[indexIdent] = index;
};
} | javascript | {
"resource": ""
} | |
q27647 | jURL | train | function jURL(url, base /* , encoding */) {
if (base !== undefined && !(base instanceof jURL))
base = new jURL(String(base));
this._url = url;
clear.call(this);
var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
// encoding = encoding || 'utf-8'
parse.call(this, input, null, base);
} | javascript | {
"resource": ""
} |
q27648 | train | function() {
// only flush if the page is visibile
if (document.visibilityState === 'hidden') {
if (scope.flushPoll) {
clearInterval(scope.flushPoll);
}
} else {
scope.flushPoll = setInterval(flush, FLUSH_POLL_INTERVAL);
}
} | javascript | {
"resource": ""
} | |
q27649 | Loader | train | function Loader(regex) {
this.cache = Object.create(null);
this.map = Object.create(null);
this.requests = 0;
this.regex = regex;
} | javascript | {
"resource": ""
} |
q27650 | train | function(text, root, callback) {
var matches = this.extractUrls(text, root);
// every call to process returns all the text this loader has ever received
var done = callback.bind(null, this.map);
this.fetch(matches, done);
} | javascript | {
"resource": ""
} | |
q27651 | train | function(matches, callback) {
var inflight = matches.length;
// return early if there is no fetching to be done
if (!inflight) {
return callback();
}
// wait for all subrequests to return
var done = function() {
if (--inflight === 0) {
callback();
}
};
// start fetching all subrequests
var m, req, url;
for (var i = 0; i < inflight; i++) {
m = matches[i];
url = m.url;
req = this.cache[url];
// if this url has already been requested, skip requesting it again
if (!req) {
req = this.xhr(url);
req.match = m;
this.cache[url] = req;
}
// wait for the request to process its subrequests
req.wait(done);
}
} | javascript | {
"resource": ""
} | |
q27652 | train | function(style, url, callback) {
var text = style.textContent;
var done = function(text) {
style.textContent = text;
callback(style);
};
this.resolve(text, url, done);
} | javascript | {
"resource": ""
} | |
q27653 | train | function(text, base, map) {
var matches = this.loader.extractUrls(text, base);
var match, url, intermediate;
for (var i = 0; i < matches.length; i++) {
match = matches[i];
url = match.url;
// resolve any css text to be relative to the importer, keep absolute url
intermediate = urlResolver.resolveCssText(map[url], url, true);
// flatten intermediate @imports
intermediate = this.flatten(intermediate, base, map);
text = text.replace(match.matched, intermediate);
}
return text;
} | javascript | {
"resource": ""
} | |
q27654 | extend | train | function extend(prototype, api) {
if (prototype && api) {
// use only own properties of 'api'
Object.getOwnPropertyNames(api).forEach(function(n) {
// acquire property descriptor
var pd = Object.getOwnPropertyDescriptor(api, n);
if (pd) {
// clone property via descriptor
Object.defineProperty(prototype, n, pd);
// cache name-of-method for 'super' engine
if (typeof pd.value == 'function') {
// hint the 'super' engine
pd.value.nom = n;
}
}
});
}
return prototype;
} | javascript | {
"resource": ""
} |
q27655 | copyProperty | train | function copyProperty(inName, inSource, inTarget) {
var pd = getPropertyDescriptor(inSource, inName);
Object.defineProperty(inTarget, inName, pd);
} | javascript | {
"resource": ""
} |
q27656 | getPropertyDescriptor | train | function getPropertyDescriptor(inObject, inName) {
if (inObject) {
var pd = Object.getOwnPropertyDescriptor(inObject, inName);
return pd || getPropertyDescriptor(Object.getPrototypeOf(inObject), inName);
}
} | javascript | {
"resource": ""
} |
q27657 | $super | train | function $super(arrayOfArgs) {
// since we are thunking a method call, performance is important here:
// memoize all lookups, once memoized the fast path calls no other
// functions
//
// find the caller (cannot be `strict` because of 'caller')
var caller = $super.caller;
// memoized 'name of method'
var nom = caller.nom;
// memoized next implementation prototype
var _super = caller._super;
if (!_super) {
if (!nom) {
nom = caller.nom = nameInThis.call(this, caller);
}
if (!nom) {
console.warn('called super() on a method not installed declaratively (has no .nom property)');
}
// super prototype is either cached or we have to find it
// by searching __proto__ (at the 'top')
// invariant: because we cache _super on fn below, we never reach
// here from inside a series of calls to super(), so it's ok to
// start searching from the prototype of 'this' (at the 'top')
// we must never memoize a null super for this reason
_super = memoizeSuper(caller, nom, getPrototypeOf(this));
}
// our super function
var fn = _super[nom];
if (fn) {
// memoize information so 'fn' can call 'super'
if (!fn._super) {
// must not memoize null, or we lose our invariant above
memoizeSuper(fn, nom, _super);
}
// invoke the inherited method
// if 'fn' is not function valued, this will throw
return fn.apply(this, arrayOfArgs || []);
}
} | javascript | {
"resource": ""
} |
q27658 | train | function(anew, old, className) {
if (old) {
old.classList.remove(className);
}
if (anew) {
anew.classList.add(className);
}
} | javascript | {
"resource": ""
} | |
q27659 | train | function() {
var events = this.eventDelegates;
log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events);
// NOTE: host events look like bindings but really are not;
// (1) we don't want the attribute to be set and (2) we want to support
// multiple event listeners ('host' and 'instance') and Node.bind
// by default supports 1 thing being bound.
for (var type in events) {
var methodName = events[type];
PolymerGestures.addEventListener(this, type, this.element.getEventHandler(this, this, methodName));
}
} | javascript | {
"resource": ""
} | |
q27660 | train | function(obj, method, args) {
if (obj) {
log.events && console.group('[%s] dispatch [%s]', obj.localName, method);
var fn = typeof method === 'function' ? method : obj[method];
if (fn) {
fn[args ? 'apply' : 'call'](obj, args);
}
log.events && console.groupEnd();
// NOTE: dirty check right after calling method to ensure
// changes apply quickly; in a very complicated app using high
// frequency events, this can be a perf concern; in this case,
// imperative handlers can be used to avoid flushing.
Polymer.flush();
}
} | javascript | {
"resource": ""
} | |
q27661 | train | function() {
// if we have no publish lookup table, we have no attributes to take
// TODO(sjmiles): ad hoc
if (this._publishLC) {
for (var i=0, a$=this.attributes, l=a$.length, a; (a=a$[i]) && i<l; i++) {
this.attributeToProperty(a.name, a.value);
}
}
} | javascript | {
"resource": ""
} | |
q27662 | train | function(name, value) {
// try to match this attribute to a property (attributes are
// all lower-case, so this is case-insensitive search)
var name = this.propertyForAttribute(name);
if (name) {
// filter out 'mustached' values, these are to be
// replaced with bound-data and are not yet values
// themselves
if (value && value.search(scope.bindPattern) >= 0) {
return;
}
// get original value
var currentValue = this[name];
// deserialize Boolean or Number values from attribute
var value = this.deserializeValue(value, currentValue);
// only act if the value has changed
if (value !== currentValue) {
// install new value (has side-effects)
this[name] = value;
}
}
} | javascript | {
"resource": ""
} | |
q27663 | train | function(value, inferredType) {
if (inferredType === 'boolean') {
return value ? '' : undefined;
} else if (inferredType !== 'object' && inferredType !== 'function'
&& value !== undefined) {
return value;
}
} | javascript | {
"resource": ""
} | |
q27664 | train | function(name) {
var inferredType = typeof this[name];
// try to intelligently serialize property value
var serializedValue = this.serializeValue(this[name], inferredType);
// boolean properties must reflect as boolean attributes
if (serializedValue !== undefined) {
this.setAttribute(name, serializedValue);
// TODO(sorvell): we should remove attr for all properties
// that have undefined serialization; however, we will need to
// refine the attr reflection system to achieve this; pica, for example,
// relies on having inferredType object properties not removed as
// attrs.
} else if (inferredType === 'boolean') {
this.removeAttribute(name);
}
} | javascript | {
"resource": ""
} | |
q27665 | resolveBindingValue | train | function resolveBindingValue(oldValue, value) {
if (value === undefined && oldValue === null) {
return value;
}
return (value === null || value === undefined) ? oldValue : value;
} | javascript | {
"resource": ""
} |
q27666 | train | function() {
var n$ = this._observeNames;
if (n$ && n$.length) {
var o = this._propertyObserver = new CompoundObserver(true);
this.registerObserver(o);
// TODO(sorvell): may not be kosher to access the value here (this[n]);
// previously we looked at the descriptor on the prototype
// this doesn't work for inheritance and not for accessors without
// a value property
for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) {
o.addPath(this, n);
this.observeArrayValue(n, this[n], null);
}
}
} | javascript | {
"resource": ""
} | |
q27667 | train | function(name, observable, resolveFn) {
var privateName = name + '_';
var privateObservable = name + 'Observable_';
// Present for properties which are computed and published and have a
// bound value.
var privateComputedBoundValue = name + 'ComputedBoundObservable_';
this[privateObservable] = observable;
var oldValue = this[privateName];
// observable callback
var self = this;
function updateValue(value, oldValue) {
self[privateName] = value;
var setObserveable = self[privateComputedBoundValue];
if (setObserveable && typeof setObserveable.setValue == 'function') {
setObserveable.setValue(value);
}
self.emitPropertyChangeRecord(name, value, oldValue);
}
// resolve initial value
var value = observable.open(updateValue);
if (resolveFn && !areSameValue(oldValue, value)) {
var resolvedValue = resolveFn(oldValue, value);
if (!areSameValue(value, resolvedValue)) {
value = resolvedValue;
if (observable.setValue) {
observable.setValue(value);
}
}
}
updateValue(value, oldValue);
// register and return observable
var observer = {
close: function() {
observable.close();
self[privateObservable] = undefined;
self[privateComputedBoundValue] = undefined;
}
};
this.registerObserver(observer);
return observer;
} | javascript | {
"resource": ""
} | |
q27668 | train | function(template) {
// ensure template is decorated (lets' things like <tr template ...> work)
HTMLTemplateElement.decorate(template);
// ensure a default bindingDelegate
var syntax = this.syntax || (!template.bindingDelegate &&
this.element.syntax);
var dom = template.createInstance(this, syntax);
var observers = dom.bindings_;
for (var i = 0; i < observers.length; i++) {
this.registerObserver(observers[i]);
}
return dom;
} | javascript | {
"resource": ""
} | |
q27669 | train | function() {
if (!this._unbound) {
log.unbind && console.log('[%s] asyncUnbindAll', this.localName);
this._unbindAllJob = this.job(this._unbindAllJob, this.unbindAll, 0);
}
} | javascript | {
"resource": ""
} | |
q27670 | train | function(job, callback, wait) {
if (typeof job === 'string') {
var n = '___' + job;
this[n] = Polymer.job.call(this, this[n], callback, wait);
} else {
// TODO(sjmiles): suggest we deprecate this call signature
return Polymer.job.call(this, job, callback, wait);
}
} | javascript | {
"resource": ""
} | |
q27671 | train | function() {
if (this.templateInstance && this.templateInstance.model) {
console.warn('Attributes on ' + this.localName + ' were data bound ' +
'prior to Polymer upgrading the element. This may result in ' +
'incorrect binding types.');
}
this.created();
this.prepareElement();
if (!this.ownerDocument.isStagingDocument) {
this.makeElementReady();
}
} | javascript | {
"resource": ""
} | |
q27672 | train | function() {
if (this._elementPrepared) {
console.warn('Element already prepared', this.localName);
return;
}
this._elementPrepared = true;
// storage for shadowRoots info
this.shadowRoots = {};
// install property observers
this.createPropertyObserver();
this.openPropertyObserver();
// install boilerplate attributes
this.copyInstanceAttributes();
// process input attributes
this.takeAttributes();
// add event listeners
this.addHostListeners();
} | javascript | {
"resource": ""
} | |
q27673 | train | function(name, oldValue) {
// TODO(sjmiles): adhoc filter
if (name !== 'class' && name !== 'style') {
this.attributeToProperty(name, this.getAttribute(name));
}
if (this.attributeChanged) {
this.attributeChanged.apply(this, arguments);
}
} | javascript | {
"resource": ""
} | |
q27674 | train | function(p) {
if (p && p.element) {
this.parseDeclarations(p.__proto__);
p.parseDeclaration.call(this, p.element);
}
} | javascript | {
"resource": ""
} | |
q27675 | train | function(template) {
if (template) {
// make a shadow root
var root = this.createShadowRoot();
// stamp template
// which includes parsing and applying MDV bindings before being
// inserted (to avoid {{}} in attribute values)
// e.g. to prevent <img src="images/{{icon}}"> from generating a 404.
var dom = this.instanceTemplate(template);
// append to shadow dom
root.appendChild(dom);
// perform post-construction initialization tasks on shadow root
this.shadowRootReady(root, template);
// return the created shadow root
return root;
}
} | javascript | {
"resource": ""
} | |
q27676 | train | function(node, listener) {
var observer = new MutationObserver(function(mutations) {
listener.call(this, observer, mutations);
observer.disconnect();
}.bind(this));
observer.observe(node, {childList: true, subtree: true});
} | javascript | {
"resource": ""
} | |
q27677 | train | function(callback) {
var template = this.fetchTemplate();
var content = template && this.templateContent();
if (content) {
this.convertSheetsToStyles(content);
var styles = this.findLoadableStyles(content);
if (styles.length) {
var templateUrl = template.ownerDocument.baseURI;
return Polymer.styleResolver.loadStyles(styles, templateUrl, callback);
}
}
if (callback) {
callback();
}
} | javascript | {
"resource": ""
} | |
q27678 | train | function() {
this.sheets = this.findNodes(SHEET_SELECTOR);
this.sheets.forEach(function(s) {
if (s.parentNode) {
s.parentNode.removeChild(s);
}
});
} | javascript | {
"resource": ""
} | |
q27679 | train | function(name, extendee) {
// build side-chained lists to optimize iterations
this.optimizePropertyMaps(this.prototype);
this.createPropertyAccessors(this.prototype);
// install mdv delegate on template
this.installBindingDelegate(this.fetchTemplate());
// install external stylesheets as if they are inline
this.installSheets();
// adjust any paths in dom from imports
this.resolveElementPaths(this);
// compile list of attributes to copy to instances
this.accumulateInstanceAttributes();
// parse on-* delegates declared on `this` element
this.parseHostEvents();
//
// install a helper method this.resolvePath to aid in
// setting resource urls. e.g.
// this.$.image.src = this.resolvePath('images/foo.png')
this.addResolvePathApi();
// under ShadowDOMPolyfill, transforms to approximate missing CSS features
if (hasShadowDOMPolyfill) {
WebComponents.ShadowCSS.shimStyling(this.templateContent(), name,
extendee);
}
// allow custom element access to the declarative context
if (this.prototype.registerCallback) {
this.prototype.registerCallback(this);
}
} | javascript | {
"resource": ""
} | |
q27680 | train | function(extnds) {
var prototype = this.findBasePrototype(extnds);
if (!prototype) {
// create a prototype based on tag-name extension
var prototype = HTMLElement.getPrototypeForTag(extnds);
// insert base api in inheritance chain (if needed)
prototype = this.ensureBaseApi(prototype);
// memoize this base
memoizedBases[extnds] = prototype;
}
return prototype;
} | javascript | {
"resource": ""
} | |
q27681 | train | function(prototype) {
if (prototype.PolymerBase) {
return prototype;
}
var extended = Object.create(prototype);
// we need a unique copy of base api for each base prototype
// therefore we 'extend' here instead of simply chaining
api.publish(api.instance, extended);
// TODO(sjmiles): sharing methods across prototype chains is
// not supported by 'super' implementation which optimizes
// by memoizing prototype relationships.
// Probably we should have a version of 'extend' that is
// share-aware: it could study the text of each function,
// look for usage of 'super', and wrap those functions in
// closures.
// As of now, there is only one problematic method, so
// we just patch it manually.
// To avoid re-entrancy problems, the special super method
// installed is called `mixinSuper` and the mixin method
// must use this method instead of the default `super`.
this.mixinMethod(extended, prototype, api.instance.mdv, 'bind');
// return buffed-up prototype
return extended;
} | javascript | {
"resource": ""
} | |
q27682 | train | function(name, extendee) {
var info = {
prototype: this.prototype
}
// native element must be specified in extends
var typeExtension = this.findTypeExtension(extendee);
if (typeExtension) {
info.extends = typeExtension;
}
// register the prototype with HTMLElement for name lookup
HTMLElement.register(name, this.prototype);
// register the custom type
this.ctor = document.registerElement(name, info);
} | javascript | {
"resource": ""
} | |
q27683 | train | function(element, check, go) {
var shouldAdd = element.__queue && !element.__queue.check;
if (shouldAdd) {
queueForElement(element).push(element);
element.__queue.check = check;
element.__queue.go = go;
}
return (this.indexOf(element) !== 0);
} | javascript | {
"resource": ""
} | |
q27684 | train | function(element) {
var readied = this.remove(element);
if (readied) {
element.__queue.flushable = true;
this.addToFlushQueue(readied);
this.check();
}
} | javascript | {
"resource": ""
} | |
q27685 | train | function() {
var e$ = [];
for (var i=0, l=elements.length, e; (i<l) &&
(e=elements[i]); i++) {
if (e.__queue && !e.__queue.flushable) {
e$.push(e);
}
}
return e$;
} | javascript | {
"resource": ""
} | |
q27686 | forceReady | train | function forceReady(timeout) {
if (timeout === undefined) {
queue.ready();
return;
}
var handle = setTimeout(function() {
queue.ready();
}, timeout);
Polymer.whenReady(function() {
clearTimeout(handle);
});
} | javascript | {
"resource": ""
} |
q27687 | _import | train | function _import(urls, callback) {
if (urls && urls.length) {
var frag = document.createDocumentFragment();
for (var i=0, l=urls.length, url, link; (i<l) && (url=urls[i]); i++) {
link = document.createElement('link');
link.rel = 'import';
link.href = url;
frag.appendChild(link);
}
importElements(frag, callback);
} else if (callback) {
callback();
}
} | javascript | {
"resource": ""
} |
q27688 | slice | train | function slice(what, start) {
for (var j = 0, i = start || 0, arr = []; i < what.length; i++) {
arr[j++] = what[i];
}
return arr;
} | javascript | {
"resource": ""
} |
q27689 | train | function (newValue) {
// and no inheritance is involved
if (this === self) {
// notify the method but ...
var value = oldValue;
updateValue(newValue);
// ... do not update the get value
oldValue = value;
} else {
// with inheritance, simply set the property
// as if it was a regular assignment operation
setValue(this, prop, newValue);
}
} | javascript | {
"resource": ""
} | |
q27690 | deepClone | train | function deepClone(item) {
let clone = item;
if (isArray(item)) {
clone = new Array(item.length);
item.forEach((child, key) => {
clone[key] = deepClone(child);
});
} else if (item && typeOf(item) === 'object') {
clone = {};
keys(item).forEach(key => {
clone[key] = deepClone(item[key]);
});
}
return clone;
} | javascript | {
"resource": ""
} |
q27691 | loadOptions | train | function loadOptions() {
chrome.storage.sync.get('options', function(data) {
var options = data.options;
document.querySelector('[data-settings=tomster]').checked = options && options.showTomster;
});
} | javascript | {
"resource": ""
} |
q27692 | storeOptions | train | function storeOptions() {
var showTomster = this.checked;
chrome.storage.sync.set({
options: { showTomster: showTomster }
}, function optionsSaved() {
console.log("saved!");
});
} | javascript | {
"resource": ""
} |
q27693 | customizeProperties | train | function customizeProperties(mixinDetails, propertyInfo) {
let newMixinDetails = [];
let neededProperties = {};
let groups = propertyInfo.groups || [];
let skipProperties = propertyInfo.skipProperties || [];
let skipMixins = propertyInfo.skipMixins || [];
if (groups.length) {
mixinDetails[0].expand = false;
}
groups.forEach(group => {
group.properties.forEach(prop => {
neededProperties[prop] = true;
});
});
mixinDetails.forEach(mixin => {
let newProperties = [];
mixin.properties.forEach(item => {
// If 2.10.0 or 2.10.x but < 2.11
if (compareVersion(VERSION, '2.10.0') === 0 ||
(compareVersion(VERSION, '2.10.0') === 1 && compareVersion(VERSION, '2.11.0') === -1)) {
skipProperties = twoTenfilterHack(item.name, skipProperties);
}
if (skipProperties.indexOf(item.name) !== -1) {
return true;
}
if (!item.overridden && neededProperties.hasOwnProperty(item.name) && neededProperties[item.name]) {
neededProperties[item.name] = item;
} else {
newProperties.push(item);
}
});
mixin.properties = newProperties;
if (skipMixins.indexOf(mixin.name) === -1) {
newMixinDetails.push(mixin);
}
});
groups.slice().reverse().forEach(group => {
let newMixin = { name: group.name, expand: group.expand, properties: [] };
group.properties.forEach(function(prop) {
// make sure it's not `true` which means property wasn't found
if (neededProperties[prop] !== true) {
newMixin.properties.push(neededProperties[prop]);
}
});
newMixinDetails.unshift(newMixin);
});
return newMixinDetails;
} | javascript | {
"resource": ""
} |
q27694 | generateVersionsTooltip | train | function generateVersionsTooltip(versions) {
return versions.map(function(lib) {
return lib.name + " " + lib.version;
}).join("\n");
} | javascript | {
"resource": ""
} |
q27695 | setActionTitle | train | function setActionTitle(tabId) {
chrome.pageAction.setTitle({
tabId: tabId,
title: generateVersionsTooltip(activeTabs[tabId])
});
} | javascript | {
"resource": ""
} |
q27696 | relative | train | function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, '');
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
var level = 0;
while (aPath.indexOf(aRoot + '/') !== 0) {
var index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
} | javascript | {
"resource": ""
} |
q27697 | recursiveSearch | train | function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
}
else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
} else {
return mid;
}
}
else {
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
} else {
return aLow < 0 ? -1 : aLow;
}
}
} | javascript | {
"resource": ""
} |
q27698 | randomIntInRange | train | function randomIntInRange(low, high) {
return Math.round(low + (Math.random() * (high - low)));
} | javascript | {
"resource": ""
} |
q27699 | findMetaTag | train | function findMetaTag(attribute, regExp = /.*/) {
let metas = document.querySelectorAll(`meta[${attribute}]`);
for (let i = 0; i < metas.length; i++) {
let match = metas[i].getAttribute(attribute).match(regExp);
if (match) {
return metas[i];
}
}
return null;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.