_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1200 | parseBoolean | train | function parseBoolean(value, context) {
if (value === true || value === 'true') return true;
if | javascript | {
"resource": ""
} |
q1201 | handleResourceContext | train | function handleResourceContext(attrNode, context) {
let dataSource;
let lastDataSourceName;
const errorContext = context.errorContext;
if (attrNode.resource) {
if ('subFilters' in attrNode) {
throw new ImplementationError(
'Adding subFilters for included sub-resource is not allowed' + context.errorContext
);
}
if ('primaryKey' in attrNode) {
throw new ImplementationError(
'Overwriting primaryKey for included sub-resource is not allowed' + context.errorContext
);
}
} else if (!('primaryKey' in attrNode)) {
throw new ImplementationError('Missing primaryKey' + context.errorContext);
}
if (attrNode.dataSources) {
Object.keys(attrNode.dataSources).forEach(dataSourceName => {
lastDataSourceName = dataSourceName;
context.dataSourceAttributes[dataSourceName] = [];
dataSource = attrNode.dataSources[dataSourceName];
if (dataSource.inherit) {
if (!attrNode.resource) {
throw new ImplementationError(
`DataSource "${dataSourceName}" is defined as "inherit" but has no included resource`
);
}
context.errorContext = ' in inherit' + errorContext;
dataSource.inherit = checkWhitelist(dataSource.inherit, ['true', 'inherit', 'replace'], context);
if (dataSource.inherit === 'true') {
dataSource.inherit = 'inherit';
}
context.errorContext = errorContext;
}
if (!dataSource.type && !dataSource.inherit) {
throw new ImplementationError(
`DataSource "${dataSourceName}" misses "type" option${context.errorContext}`
);
}
if (dataSource.joinParentKey) {
context.errorContext = ' in joinParentKey' + errorContext;
dataSource.joinParentKey = parsePrimaryKey(dataSource.joinParentKey, context);
| javascript | {
"resource": ""
} |
q1202 | handleAttributeContext | train | function handleAttributeContext(attrNode, context) {
if (!attrNode.type && attrNode.inherit !== 'inherit') attrNode.type = 'string';
if (attrNode.map) {
Object.keys(attrNode.map).forEach(mappingName => {
const mapping = attrNode.map[mappingName];
Object.keys(mapping).forEach(dataSourceName => {
if (!context.dataSourceAttributes[dataSourceName]) {
throw new ImplementationError(
`Unknown DataSource "${dataSourceName}" in map${context.errorContext}`
| javascript | {
"resource": ""
} |
q1203 | resolveKey | train | function resolveKey(key, attrNode, options, context) {
const resolvedKey = {};
key.forEach(keyAttrPath => {
const keyAttrNode = getLocalAttribute(keyAttrPath, attrNode, context);
if (keyAttrNode.multiValued) {
if (!options.allowMultiValued) {
throw new ImplementationError(
`Key attribute "${keyAttrPath.join('.')}" ` + `must not be multiValued${context.errorContext}`
);
}
if (key.length > 1) {
throw new ImplementationError(
`Composite key attribute "${keyAttrPath.join('.')}" ` +
`must not be multiValued${context.errorContext}`
);
}
}
if (keyAttrNode.map) {
Object.keys(keyAttrNode.map.default).forEach(dataSourceName => {
if (!resolvedKey[dataSourceName]) resolvedKey[dataSourceName] = [];
resolvedKey[dataSourceName].push(keyAttrNode.map.default[dataSourceName]);
});
}
if (options.neededDataSources) {
options.neededDataSources.forEach(neededDataSource => {
if (!keyAttrNode.map || !keyAttrNode.map.default[neededDataSource]) {
throw new ImplementationError(
| javascript | {
"resource": ""
} |
q1204 | resolvePrimaryKey | train | function resolvePrimaryKey(attrNode, context) {
const errorContext = context.errorContext;
context.errorContext = ' in primaryKey' + errorContext;
const neededDataSources = [];
Object.keys(attrNode.dataSources).forEach(dataSourceName => {
if (attrNode.dataSources[dataSourceName].joinParentKey) return;
neededDataSources.push(dataSourceName);
});
attrNode.resolvedPrimaryKey = resolveKey(
attrNode.primaryKey,
attrNode,
{
neededDataSources,
allowMultiValued: false
},
| javascript | {
"resource": ""
} |
q1205 | processNode | train | function processNode(attrNode, context) {
const isMainResource = context.attrPath.length === 0;
// identify/handle options-contexts: resource/sub-resource, nested-attribute, attribute:
if (attrNode.dataSources || attrNode.resource || isMainResource) {
context.errorContext = getErrorContext(isMainResource ? 'resource' : 'sub-resource', context);
context.subAttrPath = [];
context.dataSourceAttributes = {};
if (isMainResource) {
parseNode(
attrNode,
{
dataSources: null,
subFilters: parseSubFilters,
resource: checkResourceName,
primaryKey: parsePrimaryKey,
depends: parseDepends,
deprecated: parseBoolean,
permission: null,
attributes: null,
defaultLimit: parseInteger,
maxLimit: parseInteger,
defaultOrder: requestParser.order
},
context
);
} else {
parseNode(
attrNode,
{
dataSources: null,
subFilters: parseSubFilters,
resource: checkResourceName,
primaryKey: parsePrimaryKey,
parentKey: parseRelationKey,
childKey: parseRelationKey,
many: parseBoolean,
depends: parseDepends,
hidden: parseBoolean,
deprecated: parseBoolean,
permission: null,
joinVia: checkIdentifier,
attributes: null,
defaultLimit: parseInteger,
maxLimit: parseInteger,
defaultOrder: requestParser.order
},
context
);
}
handleResourceContext(attrNode, context);
} else if (attrNode.attributes) {
context.errorContext = getErrorContext('nested-attribute', context);
parseNode(
attrNode,
{
depends: parseDepends,
hidden: parseBoolean,
| javascript | {
"resource": ""
} |
q1206 | getPropertyName | train | function getPropertyName(parentName, parent, indexer) {
var propertyName = parentName || "";
if (exports.getType(parent) === "array") {
| javascript | {
"resource": ""
} |
q1207 | deps | train | function deps(s, p) {
if (!shards.map[p] || !shards.map[p].ParentShardId) return;
shards.deps[s] = lib.toFlags("add", shards.deps[s], | javascript | {
"resource": ""
} |
q1208 | buildStructureForFile | train | function buildStructureForFile(file) {
var names = [];
var targetLink;
if (file.dox.length === 0) { return false; }
file.dox.forEach(function(method){
if (method.ctx && !method.ignore) { names.push(method.ctx.name); }
});
// How deep is your love?
// If the splitted currentFile (the file we are currently rendering) path got one folder
// in the path or more, add ../ for each level found
if(file.currentFile && file.currentFile.split(path.sep).length > 1 ){
// Depth of current file
var depth = file.currentFile.split(path.sep).length,
// Create a prefix with n "../"
| javascript | {
"resource": ""
} |
q1209 | commit | train | function commit(result) {
var url = result.html_url
//user opted not to commit anything
if (argv.b || argv.bare) {
return Promise.resolve(url)
}
return getMessage().then(function(message) {
return gitCommit({
message: message,
url: url + '.git'
}).catch(function() {
| javascript | {
"resource": ""
} |
q1210 | train | function(s) {
s = s.replace(/\s/, "");
var v = window.parseFloat(s);
| javascript | {
"resource": ""
} |
|
q1211 | train | function(el, properties) {
var duration = 0;
for (var i = 0; i < properties.length; i++) {
// Get raw CSS value
var value = el.css(properties[i]);
if (!value) continue;
// Multiple transitions--pick the longest
if (value.indexOf(",") !== -1) {
var values = value.split(",");
var durations = (function(){
var results = [];
for (var i = 0; i < values.length; i++) {
var duration = parseTime(values[i]);
| javascript | {
"resource": ""
} |
|
q1212 | train | function(handleObj) {
var el = $(this);
var fired = false;
// Mark element as being in transition
el.data("trend", true);
// Calculate a fallback duration. + 20 because some browsers fire
// timeouts faster than transitionend.
var time =
parseProperties(el, transitionDurationProperties) +
parseProperties(el, transitionDelayProperties) +
20;
var cb = function(e) {
// transitionend events can be sent for each property. Let's just
// skip all but the first. Also handles the timeout callback.
if (fired) return;
// Child elements that also have transitions can be fired before we
// complete. This will catch and | javascript | {
"resource": ""
} |
|
q1213 | ajax | train | function ajax( opts ) {
const method = (opts.method || 'get').toUpperCase()
const {
url,
body,
contentType,
extraHeaders,
useBearer = true,
bearer
} = opts || {}
let requestInit = {
method,
headers: fetchHeaders({
method,
contentType,
extraHeaders,
useBearer,
bearer
}),
credentials: 'same-origin'
}
if( method != 'GET' && method != 'HEAD' && method != 'OPTIONS') {
requestInit.body = body
}
| javascript | {
"resource": ""
} |
q1214 | postJson | train | function postJson({ url, payload, contentType, useBearer }) {
return ajax({
| javascript | {
"resource": ""
} |
q1215 | makeFormData | train | function makeFormData( payload ) {
let body = new FormData()
| javascript | {
"resource": ""
} |
q1216 | postForm | train | function postForm({ url, payload, useBearer }) {
return ajax({
url,
| javascript | {
"resource": ""
} |
q1217 | nodeExtent | train | function nodeExtent(graph, attribute) {
if (!isGraph(graph))
throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.');
var attributes = [].concat(attribute);
var nodes = graph.nodes(),
node,
data,
value,
key,
a,
i,
l;
var results = {};
for (a = 0; a < attributes.length; a++) {
| javascript | {
"resource": ""
} |
q1218 | edgeExtent | train | function edgeExtent(graph, attribute) {
if (!isGraph(graph))
throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.');
var attributes = [].concat(attribute);
var edges = graph.edges(),
edge,
data,
value,
key,
a,
i,
l;
var results = {};
for (a = 0; a < attributes.length; a++) {
| javascript | {
"resource": ""
} |
q1219 | ScalarMultiple | train | function ScalarMultiple(bytes, discrim) {
var order = ec.curve.n;
for (var i = 0; i <= 0xFFFFFFFF; i++) {
// We hash the bytes to find a 256 bit number, looping until we are sure it
// is less than the order of the curve.
var hasher = new Sha512().add(bytes);
// If the optional discriminator index was passed in, update the hash.
if (discrim !== undefined) {
hasher.addU32(discrim);
}
hasher.addU32(i);
var key = | javascript | {
"resource": ""
} |
q1220 | getValue | train | function getValue(fromObject, fromKey) {
var regDot = /\./g
, regFinishArray = /.+(\[\])/g
, keys
, key
, result
, lastValue
;
keys = fromKey.split(regDot); | javascript | {
"resource": ""
} |
q1221 | fillArrayWithNull | train | function fillArrayWithNull( arr, toIndex ) {
for( | javascript | {
"resource": ""
} |
q1222 | train | function(session, args, callback) {
session.stdout().write('Hello, ' + | javascript | {
"resource": ""
} |
|
q1223 | modularity | train | function modularity(graph, options) {
// Handling errors
if (!isGraph(graph))
throw new Error('graphology-metrics/modularity: the given graph is not a valid graphology instance.');
if (graph.multi)
throw new Error('graphology-metrics/modularity: multi graphs are not handled.');
if (!graph.size)
throw new Error('graphology-metrics/modularity: the given graph has no edges.');
// Solving options
options = defaults({}, options, DEFAULTS);
var communities,
nodes = graph.nodes(),
edges = graph.edges(),
i,
l;
// Do we have a community mapping?
if (typeof options.communities === 'object') {
communities = options.communities;
}
// Else we need to extract it from the graph
else {
communities = {};
for (i = 0, l = nodes.length; i < l; i++)
communities[nodes[i]] = graph.getNodeAttribute(nodes[i], options.attributes.community);
}
var M = 0,
Q = 0,
internalW = {},
totalW = {},
bounds,
node1, node2, edge,
community1, community2,
w, weight;
for (i = 0, l = edges.length; i < l; i++) {
edge = edges[i];
bounds = graph.extremities(edge);
node1 = bounds[0];
node2 = bounds[1];
if (node1 === node2)
continue;
community1 = communities[node1];
community2 = communities[node2];
if (community1 === undefined) | javascript | {
"resource": ""
} |
q1224 | train | function (destCtx, debug) {
if (!this.visible) {
return;
}
// auto goto next frame
if (this.currentAnimName.length) {
this.advanceFrame(this.currentAnimName);
}
var w = this.getCurrentWidth(),
scaledW = w * this.scale,
h = this.getCurrentHeight(),
scaledH = h * this.scale,
subScaledW = (scaledW / 2) | 0,
subScaledH = (scaledH / 2) | 0,
x = this.getCurrentOffsetX(),
y = this.getCurrentOffsetY(),
drawX = this.x + this.getCurrentShiftX(),
drawY = this.y + this.getCurrentShiftY(),
mapOffsetX = this.currentMap && this.currentMap.viewportX || 0,
mapOffsetY = this.currentMap && this.currentMap.viewportY || 0;
| javascript | {
"resource": ""
} |
|
q1225 | abstractDegreeCentrality | train | function abstractDegreeCentrality(assign, method, graph, options) {
var name = method + 'Centrality';
if (!isGraph(graph))
throw new Error('graphology-centrality/' + name + ': the given graph is not a valid graphology instance.');
if (method !== 'degree' && graph.type === 'undirected')
throw new Error('graphology-centrality/' + name + ': cannot compute ' + method + ' centrality on an undirected graph.');
// Solving options
options = options || {};
var attributes = options.attributes || {};
var centralityAttribute = attributes.centrality || name;
// Variables
var order = graph.order,
nodes = graph.nodes(),
getDegree = graph[method].bind(graph),
centralities = {};
if (order === 0)
return assign ? undefined | javascript | {
"resource": ""
} |
q1226 | simpleSizeForMultiGraphs | train | function simpleSizeForMultiGraphs(graph) {
var nodes = graph.nodes(),
size = 0,
i,
l;
for (i = | javascript | {
"resource": ""
} |
q1227 | abstractDensity | train | function abstractDensity(type, multi, graph) {
var order,
size;
// Retrieving order & size
if (arguments.length > 3) {
order = graph;
size = arguments[3];
if (typeof order !== 'number')
throw new Error('graphology-metrics/density: given order is not a number.');
if (typeof size !== 'number')
throw new Error('graphology-metrics/density: given size is not a number.');
}
else {
if (!isGraph(graph))
throw new Error('graphology-metrics/density: given graph is not a valid graphology instance.');
order = graph.order;
size = graph.size;
if (graph.multi && multi === false)
size = simpleSizeForMultiGraphs(graph);
}
// When the graph has only one node, its density is 0
if (order < 2)
| javascript | {
"resource": ""
} |
q1228 | Logger | train | function Logger( configuration, channels = [] ) {
this.levels = { ...levels, ...configuration.get( 'logging.levels' ) };
this.queueSize_ = 100;
this.channels_ = channels;
this.counter_ = 0;
this.messageQueue_ = [];
this.threshold_ = 0;
this.tags_ = {};
| javascript | {
"resource": ""
} |
q1229 | getDatabase | train | function getDatabase() {
var mongoAdapter = this;
expect(arguments).to.have.length(
0,
'Invalid arguments length when getting a database in a MongoAdapter ' +
'(it has to be passed no arguments)'
);
return new Promise(function (resolve, reject) {
if (_databaseIsLocked || !_database) {
mongoAdapter | javascript | {
"resource": ""
} |
q1230 | openConnection | train | function openConnection() {
expect(arguments).to.have.length(
0,
'Invalid arguments length when opening a connection in a MongoAdapter ' +
'(it has to be passed no arguments)'
);
return new Promise(function (resolve, reject) {
if (_databaseIsLocked) {
_databaseRequestQueue.push(function () {
openConnection().then(resolve).catch(reject);
});
} else if (_database) {
resolve();
} else {
_databaseIsLocked = true;
MongoClient
.connect(connectionUrl, connectionOptions)
| javascript | {
"resource": ""
} |
q1231 | closeConnection | train | function closeConnection() {
expect(arguments).to.have.length(
0,
'Invalid arguments length when closing a connection in a MongoAdapter ' +
'(it has to be passed no arguments)'
);
return new Promise(function (resolve, reject) {
if (_databaseIsLocked) {
_databaseRequestQueue.push(function () {
closeConnection()
.then(resolve) | javascript | {
"resource": ""
} |
q1232 | loadEntity | train | function loadEntity(Entity) {
expect(arguments).to.have.length(
1,
'Invalid arguments length when loading an entity in a ' +
'MongoAdapter (it has to be passed 1 argument)'
);
expect(Entity).to.be.a(
'function',
'Invalid argument "Entity" when loading an entity in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(classes.isGeneral(entity.models.Entity, Entity)).to.be.equal(
true,
'Invalid argument "Entity" when loading an entity in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(Entity.dataName).to.not.equal(
'',
'The dataName of an Entity cannot be an empty string in a MongoAdapter'
);
expect(Entity.dataName).to.not.match(
/^system\./,
'The dataName of an Entity cannot start with "system." in a MongoAdapter'
| javascript | {
"resource": ""
} |
q1233 | loadEntityAttribute | train | function loadEntityAttribute(Entity, attribute) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when loading an entity attribute in a ' +
'MongoAdapter (it has to be passed 2 arguments)'
);
expect(Entity).to.be.a(
'function',
'Invalid argument "Entity" when loading an entity in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(classes.isGeneral(entity.models.Entity, Entity)).to.be.equal(
true,
'Invalid argument "Entity" when loading an entity attribute in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(attribute).to.be.an.instanceOf(
Attribute,
'Invalid argument "attribute" when loading an entity attribute in a ' +
'MongoAdapter (it has to be an Attribute instance)'
);
var dataName = attribute.getDataName(Entity.adapterName);
expect(dataName).to.not.match(
/^\$/,
'The dataName of an Attribute cannot start with "$" in a MongoAdapter'
);
expect(dataName).to.not.contain(
'.',
'The dataName of an Attribute cannot contain "." in a MongoAdapter'
);
expect(dataName).to.not.contain(
'\0',
'The dataName of an Attribute cannot contain "\0" in a MongoAdapter'
);
expect(dataName).to.not.equal(
'Entity',
'The dataName of an Attribute cannot be equal to "Entity" in a ' +
'MongoAdapter' | javascript | {
"resource": ""
} |
q1234 | insertObject | train | function insertObject(entityObject) {
var mongoAdapter = this;
expect(arguments).to.have.length(
1,
'Invalid arguments length when inserting an object in a MongoAdapter ' +
'(it has to be passed 1 argument)'
);
return new Promise(function (resolve, reject) {
expect(entityObject).to.be.an.instanceOf(
Entity,
'Invalid argument "entityObject" when inserting an object in a ' +
'MongoAdapter (it has to be an Entity instance)'
);
var EntityClass = entityObject.Entity;
mongoAdapter
.getDatabase()
.then(function (database) {
return database
.collection(getEntityCollectionName(EntityClass))
| javascript | {
"resource": ""
} |
q1235 | updateObject | train | function updateObject(entityObject) {
var mongoAdapter = this;
expect(arguments).to.have.length(
1,
'Invalid arguments length when updating an object in a MongoAdapter ' +
'(it has to be passed 1 argument)'
);
return new Promise(function (resolve, reject) {
expect(entityObject).to.be.an.instanceOf(
Entity,
'Invalid argument "entityObject" when updating an object in a ' +
'MongoAdapter (it has to be an Entity instance)'
);
var EntityClass = entityObject.Entity;
mongoAdapter
.getDatabase()
.then(function (database) {
return database
.collection(getEntityCollectionName(EntityClass))
.updateOne(
| javascript | {
"resource": ""
} |
q1236 | objectToDocument | train | function objectToDocument(entityObject, onlyDirty) {
expect(arguments).to.have.length.below(
3,
'Invalid arguments length when converting an entity object in a ' +
'MongoDB document (it has to be passed less than 3 arguments)'
);
expect(entityObject).to.be.an.instanceOf(
Entity,
'Invalid argument "entityObject" when converting an entity object in a ' +
'MongoDB document (it has to be an Entity instances)'
);
if (onlyDirty) {
expect(onlyDirty).to.be.a(
'boolean',
'Invalid argument "onlyDirty" when converting an entity object in a ' +
'MongoDB document (it has to be a boolean)'
);
}
var document = {};
var entityAttributes = entityObject.Entity.attributes;
for (var attributeName in entityAttributes) {
if (!onlyDirty || entityObject.isDirty(attributeName)) {
var attribute | javascript | {
"resource": ""
} |
q1237 | getObject | train | function getObject(EntityClass, query) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when inserting an object in a MongoAdapter ' +
'(it has to be passed 2 arguments)'
);
var cursor;
var document;
function findDocument(db) {
cursor = _buildCursor(db, EntityClass, query);
return cursor.next();
}
function checkNotEmpty(doc) {
// save document
document = doc;
// check for no result
if (doc === null) {
throw new QueryError('Object does not exist');
}
}
function checkNotMultiple() {
// check for multiple results
return cursor.hasNext()
.then(function (hasNext) {
| javascript | {
"resource": ""
} |
q1238 | findObjects | train | function findObjects(EntityClass, query, params) {
expect(arguments).to.have.length.within(
2,
3,
'Invalid arguments length when inserting an object in a MongoAdapter ' +
'(it has to be passed 2 or 3 arguments)'
);
function findDocuments(db) {
// cleaning params
params = params || {};
params.sort = params.sort || {id: 1};
params.skip = params.skip || 0;
params.limit = params.limit || 0;
if (params.sort.hasOwnProperty('id')) {
params.sort._id = params.sort.id;
delete params.sort.id;
}
return _buildCursor(db, EntityClass, query, params)
.skip(params.skip)
.limit(params.limit)
.sort(params.sort)
| javascript | {
"resource": ""
} |
q1239 | _buildCursor | train | function _buildCursor(db, EntityClass, query) {
// copy query to not mess with user's object
query = objects.copy(query);
// rename id field
if (query.hasOwnProperty('id')) {
query._id = query.id;
delete query.id;
} | javascript | {
"resource": ""
} |
q1240 | documentToObject | train | function documentToObject(document, adapterName) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when converting a MongoDB document into ' +
'an entity object (it has to be passed 2 arguments)'
);
var obj = {};
// replace `_id` with `id`
if (document.hasOwnProperty('_id')) {
obj.id = document._id;
}
// get document class
var EntityClass = Entity.getSpecialization(document.Entity);
// loop through entity's attributes and replace with parsed values
var attributes = EntityClass.attributes;
for (var attrName in attributes) {
if (attributes.hasOwnProperty(attrName)) {
| javascript | {
"resource": ""
} |
q1241 | getEntityCollectionName | train | function getEntityCollectionName(Entity) {
expect(arguments).to.have.length(
1,
'Invalid arguments length when getting the collection name of an Entity ' +
'class (it has to be passed 1 argument)'
);
expect(Entity).to.be.a(
'function',
'Invalid argument "Entity" when getting the collection name of an ' +
'Entity (it has to be an Entity class)'
);
expect(classes.isGeneral(entity.models.Entity, Entity)).to.equal(
true,
| javascript | {
"resource": ""
} |
q1242 | abstractWeightedDegree | train | function abstractWeightedDegree(name, assign, edgeGetter, graph, options) {
if (!isGraph(graph))
throw new Error('graphology-metrics/' + name + ': the given graph is not a valid graphology instance.');
if (edgeGetter !== 'edges' && graph.type === 'undirected')
throw new Error('graphology-metrics/' + name + ': cannot compute ' + name + ' on an undirected graph.');
var singleNode = null;
// Solving arguments
if (arguments.length === 5 && typeof arguments[4] !== 'object') {
singleNode = arguments[4];
}
else if (arguments.length === 6) {
singleNode = arguments[4];
options = arguments[5];
}
// Solving options
options = options || {};
var attributes = options.attributes || {};
var weightAttribute = attributes.weight || DEFAULT_WEIGHT_ATTRIBUTE,
weightedDegreeAttribute = attributes.weightedDegree || name;
var edges,
d,
w,
i,
l;
// Computing weighted degree for a single node
if (singleNode) {
edges = graph[edgeGetter](singleNode);
d = 0;
for (i = 0, l = edges.length; i < l; i++) {
w = graph.getEdgeAttribute(edges[i], weightAttribute);
if (typeof w === 'number')
d += w;
}
if (assign) {
graph.setNodeAttribute(singleNode, weightedDegreeAttribute, d);
| javascript | {
"resource": ""
} |
q1243 | abstractBetweennessCentrality | train | function abstractBetweennessCentrality(assign, graph, options) {
if (!isGraph(graph))
throw new Error('graphology-centrality/beetweenness-centrality: the given graph is not a valid graphology instance.');
var centralities = {};
// Solving options
options = defaults({}, options, DEFAULTS);
var weightAttribute = options.attributes.weight,
centralityAttribute = options.attributes.centrality,
normalized = options.normalized,
weighted = options.weighted;
var shortestPath = weighted ?
dijkstraShotestPath.brandes :
unweightedShortestPath.brandes;
var nodes = graph.nodes(),
node,
result,
S,
P,
sigma,
delta,
coefficient,
i,
j,
l,
m,
v,
w;
// Initializing centralities
for (i = 0, l = nodes.length; i < l; i++)
centralities[nodes[i]] = 0;
// Iterating over each node
for (i = 0, l = nodes.length; i < l; i++) {
node = nodes[i];
result = shortestPath(graph, node, weightAttribute);
S = result[0];
P = result[1];
sigma = result[2];
delta = {};
// Accumulating
for (j = 0, m = S.length; j < m; j++)
delta[S[j]] = 0;
while (S.length) {
w = S.pop();
coefficient | javascript | {
"resource": ""
} |
q1244 | train | function(session, args, callback) {
// Parse the arguments using optimist
var argv = optimist.parse(args);
// Update the environment to indicate who the specified user now is
session.env('me', | javascript | {
"resource": ""
} |
|
q1245 | subSteps | train | function subSteps (obj, items) {
util.inherits(obj, Ctx);
var key = "teamcontacts versions successors predecessors".split(" ")
, propKey = "team-contacts version-history successor-version predecessor-version".split(" ");
items.forEach(function (it) {
obj.prototype[it] = function () {
this.steps.push(it);
| javascript | {
"resource": ""
} |
q1246 | idStep | train | function idStep (obj, name, inherit) {
return function (id) {
var ctx = obj ? new | javascript | {
"resource": ""
} |
q1247 | accountOrIdStep | train | function accountOrIdStep(obj, name) {
return function (accountOrId) {
if (typeof accountOrId === 'string') {
// W3C obfuscated id
return idStep(obj, name)(accountOrId);
} else {
| javascript | {
"resource": ""
} |
q1248 | consumeBody | train | function consumeBody(body) {
if (this[DISTURBED]) {
return Body.Promise.reject(new Error(`body used already for: ${this.url}`));
}
this[DISTURBED] = true;
// body is null
if (this.body === null) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is string
if (typeof this.body === 'string') {
return Body.Promise.resolve(Buffer.from(this.body));
}
// body is blob
if (this.body instanceof Blob) {
return Body.Promise.resolve(this.body.buffer);
}
// body is buffer
if (Buffer.isBuffer(this.body)) {
return Body.Promise.resolve(this.body);
}
// istanbul ignore if: should never happen
if (!(this.body instanceof Stream)) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is stream
// get ready to actually consume the body
let accum = []; | javascript | {
"resource": ""
} |
q1249 | traverseMeshes | train | function traverseMeshes( cb ) {
object.traverse( function ( child ) {
if ( child.isMesh === true ) {
var mesh = child;
var geometry = mesh.geometry;
if ( geometry.isGeometry === true | javascript | {
"resource": ""
} |
q1250 | main | train | async function main() { // eslint-disable-line no-unused-vars
try {
// `path` is the absolute path to the executable.
const path = await which('foobar');
console.log(`The command "foobar" is located at: ${path}`);
}
| javascript | {
"resource": ""
} |
q1251 | train | function(data) {
var errors = [];
// data.Errors is populated by sails-hook-validations and data.invalidAttributes is the default
var targetAttributes = (data.Errors !== undefined) ? data.Errors : data.invalidAttributes;
for (var attributeName in targetAttributes) {
var attributes = targetAttributes[attributeName];
for (var index in attributes) {
var error | javascript | {
"resource": ""
} |
|
q1252 | initCache | train | function initCache (cachePath) {
return new Promise(function (resolve, reject) {
mkdirp(cachePath, function (err) {
if (err) {
| javascript | {
"resource": ""
} |
q1253 | createEventBufferer | train | function createEventBufferer(eventName, bufferedEvents) {
return function () { // ...
| javascript | {
"resource": ""
} |
q1254 | patchHandlebars | train | function patchHandlebars(Handlebars) {
Handlebars.JavaScriptCompiler.prototype.preamble = function() {
var out = [];
if (!this.isChild) {
var namespace = this.namespace;
// patch for handlebars
var copies = [
"helpers = helpers || {};",
"for (var key in " + namespace + ".helpers) {",
" helpers[key] = helpers[key] || " + namespace + ".helpers[key];",
"}"
].join('\n');
if (this.environment.usePartial) { copies = copies + " partials = partials || " + namespace + ".partials;"; }
if (this.options.data) { copies = copies + " data = data || {};"; }
out.push(copies);
} else | javascript | {
"resource": ""
} |
q1255 | presentRendering | train | function presentRendering(selector, classNames, speed) {
const text = document.getElementById(selector).childNodes[0];
const thisLength = text.length;
const render = (autoMarkText, cp, length) => {
let c = cp;
const r = new Rendering(document, {
className: classNames
});
const range = document.createRange();
range.setStart(autoMarkText, 0);
range.setEnd(autoMarkText, 1);
| javascript | {
"resource": ""
} |
q1256 | onClick | train | function onClick(instance) {
const self = instance;
self.wrapperNodes.forEach((n) => {
n.addEventListener(ANIMATIONEND, function thisFunction(e) {
e.target.classList.remove('bubble');
e.target.removeEventListener(ANIMATIONEND, thisFunction);
});
n.classList.add('bubble');
});
if (tooltip.getCurrentTarget() === self.wrapperNodes[0]) {
return;
}
tooltip.createTooltip(self.wrapperNodes[0], self.result.text, false);
setTimeout(() => {
| javascript | {
"resource": ""
} |
q1257 | main | train | async function main() {
// Initialize the application.
process.title = 'Which.js';
// Parse the command line arguments.
program.name('which')
.description('Find the instances of an executable in the system path.')
.version(packageVersion, '-v, --version')
.option('-a, --all', 'list all instances of executables found (instead of just the first one)')
.option('-s, --silent', 'silence the output, just return the exit code (0 if any executable is found, otherwise 1)')
.arguments('<command>').action(command => program.executable = command)
.parse(process.argv);
if | javascript | {
"resource": ""
} |
q1258 | train | function(req) {
var pk = module.exports.parsePk(req);
// Validate the required `id` parameter
if (!pk) {
var err = new Error(
'No `id` parameter provided.' +
'(Note: even if the model\'s primary key is not named `id`- ' +
'`id` should be used as the | javascript | {
"resource": ""
} |
|
q1259 | train | function (path, action, options) {
options = options || routeOpts;
options = _.extend({}, options, | javascript | {
"resource": ""
} |
|
q1260 | _getMiddlewareForShadowRoute | train | function _getMiddlewareForShadowRoute (controllerId, blueprintId) {
// Allow custom actions defined in controller to override blueprint actions.
| javascript | {
"resource": ""
} |
q1261 | getManagementToken | train | function getManagementToken(tenant, config = defaultConfig) {
const payload = {
service: tenant,
username: config.dojot.management.user
};
return (
new Buffer("jwt schema").toString("base64") +
| javascript | {
"resource": ""
} |
q1262 | removeRolePrivilege | train | function removeRolePrivilege (access, role, privilege) {
if (role === true) {
access[privilege] = {
role: []
}
return
}
| javascript | {
"resource": ""
} |
q1263 | pathJoin | train | function pathJoin(...args) {
return args
.reduce((prev, val) => {
if (typeof prev === "undefined") {
return;
}
if (val === undefined) {
return prev;
}
return typeof val === "string" || typeof val === "number"
? joinStringsWithSlash(prev, "" + val) // if string or number just keep as is
| javascript | {
"resource": ""
} |
q1264 | readScopes | train | function readScopes (root, kids, cb) {
var scopes = kids . filter (function (kid) {
return kid . charAt (0) === '@'
})
kids = kids . filter (function (kid) {
return kid . charAt (0) !== '@'
})
debug ('scopes=%j', scopes)
if (scopes . length === 0)
dz (cb) (null, kids) // prevent maybe-sync zalgo release
cb = once (cb)
var l = scopes . length
scopes . forEach (function (scope) {
var scopedir = path . resolve (root, scope)
debug ('root=%j scope=%j scopedir=%j', root, scope, scopedir)
fs . readdir (scopedir, then . bind (null, scope))
})
function then (scope, er, scopekids) {
if (er)
return cb (er)
// XXX: Not sure how old this node bug is. Maybe superstition?
| javascript | {
"resource": ""
} |
q1265 | liveAttrsUpdate | train | function liveAttrsUpdate(newVal) {
var newAttrs = live.getAttributeParts(newVal),
name;
for (name in newAttrs) {
var newValue = newAttrs[name],
// `oldAttrs` was set on the last run of setAttrs in this context
// (for this element and compute)
oldValue = oldAttrs[name];
// Only fire a callback
// if the value of the attribute has changed
if (newValue !== oldValue) {
// set on DOM attributes (dispatches an | javascript | {
"resource": ""
} |
q1266 | getDbIndexes | train | function getDbIndexes(modelKlass) {
const modelName = modelKlass.constructor.name;
return modelName === "Model"
? typed_conversions_1.hashToArray(exports.indexesForModel[modelName])
: | javascript | {
"resource": ""
} |
q1267 | getChalkColors | train | function getChalkColors(defaultConfig, overrideConfig) {
var effectiveConfig = Object.assign({}, defaultConfig, | javascript | {
"resource": ""
} |
q1268 | Subscription | train | function Subscription () {
this._id = null
this._storeRelations = null
this._memberRelations = null
this._dependencyRelations = null
this._events = {
'beforePublish': [],
'afterPublish': []
}
this._subscriptionStream = null
this._stream = null
this._lastData | javascript | {
"resource": ""
} |
q1269 | createWatchEvent | train | function createWatchEvent(type, record, event) {
const payload = Object.assign({ type, key: record.id, modelName: record.modelName, pluralName: record.pluralName, modelConstructor: record.modelConstructor, dynamicPathProperties: record.dynamicPathComponents, compositeKey: | javascript | {
"resource": ""
} |
q1270 | addPropertyToModelMeta | train | function addPropertyToModelMeta(modelName, property, meta) {
if (!exports.propertiesByModel[modelName]) {
exports.propertiesByModel[modelName] = {};
}
// TODO: investigate why we need to | javascript | {
"resource": ""
} |
q1271 | getModelProperty | train | function getModelProperty(model) {
const className = model.constructor.name;
const propsForModel = getProperties(model);
return (prop) => {
| javascript | {
"resource": ""
} |
q1272 | getProperties | train | function getProperties(model) {
const modelName = model.constructor.name;
const properties = typed_conversions_1.hashToArray(exports.propertiesByModel[modelName], "property") || [];
let parent = Object.getPrototypeOf(model.constructor);
while (parent.name) {
const subClass = new parent();
const subClassName = subClass.constructor.name;
| javascript | {
"resource": ""
} |
q1273 | createCompositeKeyString | train | function createCompositeKeyString(rec) {
const cKey = createCompositeKey(rec);
return rec.hasDynamicPath
? cKey.id +
Object.keys(cKey)
| javascript | {
"resource": ""
} |
q1274 | mockProperties | train | function mockProperties(db, config = { relationshipBehavior: "ignore" }, exceptions) {
return async (record) => {
const meta = ModelMeta_1.getModelMeta(record);
const props = meta.properties;
const recProps = {};
// below is needed to import faker library
| javascript | {
"resource": ""
} |
q1275 | addRelationshipToModelMeta | train | function addRelationshipToModelMeta(modelName, property, meta) {
if (!exports.relationshipsByModel[modelName]) {
exports.relationshipsByModel[modelName] = {};
}
// TODO: investigate why we need | javascript | {
"resource": ""
} |
q1276 | getRelationships | train | function getRelationships(model) {
const modelName = model.constructor.name;
const properties = typed_conversions_1.hashToArray(exports.relationshipsByModel[modelName], "property") || [];
let parent = Object.getPrototypeOf(model.constructor);
while (parent.name) {
const subClass = new parent();
const subClassName = subClass.constructor.name;
| javascript | {
"resource": ""
} |
q1277 | authPlayers | train | function authPlayers(channel, info) {
var code, player, token;
playerId = info.cookies.player;
token = info.cookies.token;
// Code not existing.
if (!code) {
console.log('not existing token: ', token);
return false;
}
if (code.checkedOut) {
console.log('token was already checked out: ', token);
return false;
}
// Code in use.
// usage is for LOCAL check, IsUsed for MTURK
| javascript | {
"resource": ""
} |
q1278 | idGen | train | function idGen(channel, info) {
var cid = channel.registry.generateClientId();
var cookies;
var ids;
// Return the id only if token was validated.
// More checks could be done here to ensure that token is unique in ids.
ids = channel.registry.getIds();
cookies = info.cookies;
if (cookies.player) {
| javascript | {
"resource": ""
} |
q1279 | bracketDevicePixelRatio | train | function bracketDevicePixelRatio() {
var i, scale,
brackets = [ 1, 1.3, 1.5, 2, 2.6, 3 ],
baseRatio = window.devicePixelRatio || 1;
for ( i = 0; i < brackets.length; i++ ) {
scale = brackets[ i ];
if | javascript | {
"resource": ""
} |
q1280 | setupMap | train | function setupMap( config ) {
var layerSettings, defaultSettings,
query = '',
matchLang = location.search.match( /lang=([-_a-zA-Z]+)/ );
defaultSettings = {
maxzoom: 18,
// TODO: This is UI text, and needs to be translatable.
attribution: 'Map data © <a href="http://openstreetmap.org/copyright">OpenStreetMap contributors</a>'
};
if ( matchLang ) {
query = '?lang=' + matchLang[ 1 ];
}
config = config || {};
layerSettings = {
maxZoom: config.maxzoom !== undefined ? config.maxzoom : defaultSettings.maxzoom,
// TODO: This is UI text, and needs to be translatable.
attribution: config.attribution !== undefined ? config.attribution : defaultSettings.attribution,
id: 'map-01'
};
// Add a map layer
| javascript | {
"resource": ""
} |
q1281 | gen | train | function gen(spark, fn) {
crypto.randomBytes(8, function generated(err, buff) | javascript | {
"resource": ""
} |
q1282 | train | function( tmp ) {
var _length = tmp.val.length;
return | javascript | {
"resource": ""
} |
|
q1283 | train | function( tmp ) {
return tmp.val.length | javascript | {
"resource": ""
} |
|
q1284 | train | function( tmp ) {
if ( tmp.val === '' ) return true; // allow empty because empty check does by required metheod
var reg, cardNumber, pos, digit, i, sub_total, sum = 0, strlen;
reg = new RegExp( /[^0-9]+/g );
cardNumber = tmp.val.replace( reg, '' );
strlen = cardNumber.length;
if( strlen < 13 ) return messages.creditCard;
for( i=0 ; i < strlen ; i++ ) {
pos = strlen - i;
digit = parseInt( cardNumber.substring( pos - 1, pos ), 10 );
if( i % 2 === 1 ) {
| javascript | {
"resource": ""
} |
|
q1285 | train | function( tmp, self ) {
var _arg = self.options.validators.regExp[ tmp.arg ],
_reg = new RegExp( _arg.pattern );
| javascript | {
"resource": ""
} |
|
q1286 | train | function(){
var self = this; // stored this
// Handle submit event
$( this.form ).submit( function( e ) {
// fields to be controlled transferred to global variable
FIELDS = this.querySelectorAll('[data-validetta]');
return self.init( e );
});
// real-time option control
if( this.options.realTime === true ) {
// handle change event for form elements (without checkbox)
$( this.form ).find('[data-validetta]').not('[type=checkbox]').on( 'change', function( e ) {
// field to be controlled transferred to global variable
FIELDS = $( this );
return self.init( e );
});
// handle click event for checkboxes
$( this.form ).find('[data-validetta][type=checkbox]').on( 'click', function( e | javascript | {
"resource": ""
} |
|
q1287 | train | function( e ) {
// Reset error windows from all elements
this.reset( FIELDS );
// Start control each elements
this.checkFields( e );
if( e.type !== 'submit' ) return; // if event type is not submit, break
// This is for when running remote request, return false and wait request response
else if ( this.handler === 'pending' ) return false;
// if event type is submit and handler | javascript | {
"resource": ""
} |
|
q1288 | train | function( el, e ) {
var ajaxOptions = {},
data = {},
fieldName = el.name || el.id;
if ( typeof this.remoteCache === 'undefined' ) this.remoteCache = {};
data[ fieldName ] = this.tmp.val; // Set data
// exends ajax options
ajaxOptions = $.extend( true, {}, {
data: data
}, this.options.validators.remote[ this.tmp.remote ] || {} );
// use $.param() function for generate specific cache key
var cacheKey = $.param( ajaxOptions );
// Check cache
var cache = this.remoteCache[ cacheKey ];
if ( typeof cache !== 'undefined' ) {
switch( cache.state ) {
case 'pending' : // pending means remote request not finished yet
this.handler = 'pending'; // update handler and cache event type
cache.event = e.type;
break;
case 'rejected' : // rejected means remote request could not be performed
e.preventDefault(); // we have to break submit because of throw error
throw new Error( cache.result.message );
case 'resolved' : // resolved means remote request has done
// Check to cache, if result is invalid, open an error window
| javascript | {
"resource": ""
} |
|
q1289 | train | function( ajaxOptions, cache, el, fieldName, e ) {
var self = this;
$( this.tmp.parent ).addClass('validetta-pending');
// cache xhr
this.xhr[ fieldName ] = $.ajax( ajaxOptions )
.done( function( result ) {
if( typeof result !== 'object' ) result = JSON.parse( result );
cache.state = 'resolved';
cache.result = result;
if ( cache.event === 'submit' ) {
self.handler = false;
$( self.form ).trigger('submit');
}
else if( | javascript | {
"resource": ""
} |
|
q1290 | train | function( el, error ) {
// We want display errors ?
if ( !this.options.showErrorMessages ) {
// because of form not valid, set handler true for break submit
this.handler = true;
return;
}
var elParent = this.parents( el );
// If the parent element undefined, that means el is an object. So we need to transform to the element
if( typeof elParent === 'undefined' ) elParent = el[0].parentNode;
// if there is an error window which previously opened for el, return
if ( elParent.querySelectorAll( '.'+ this.options.errorTemplateClass ).length ) return;
// Create the error window object which will be appear
| javascript | {
"resource": ""
} |
|
q1291 | train | function( el ) {
var _errorMessages = {};
// if el is undefined ( This is the process of resetting all <form> )
// or el is an object that has element more than one
// and these elements are not checkbox
if( typeof el === 'undefined' || ( el.length > 1 && el[0].type !== 'checkbox' ) ) {
_errorMessages = this.form.querySelectorAll( '.'+ this.options.errorTemplateClass );
}
else {
_errorMessages = this.parents( el[0] ).querySelectorAll( '.'+ this.options.errorTemplateClass );
| javascript | {
"resource": ""
} |
|
q1292 | train | function( el ) {
var upLength = parseInt( el.getAttribute( 'data-vd-parent-up' ), 10 ) || 0;
for ( var i = 0; i | javascript | {
"resource": ""
} |
|
q1293 | shouldBeIncluded | train | function shouldBeIncluded(file) {
let isIncluded = false
let isIgnored = false
if (hasIgnorePattern) {
return !ignorePattern.test(file)
| javascript | {
"resource": ""
} |
q1294 | buildPrefix | train | function buildPrefix(depth, bottom) {
if (!shouldIndent) {
return ''
}
let prefix = bottom ? BOX_BOTTOM_LEFT : BOX_INTERSECTION
let spacing = []
let spaceIndex = 0
while(spaceIndex < depth) {
| javascript | {
"resource": ""
} |
q1295 | shouldBeIncluded | train | function shouldBeIncluded(file) {
if (!showAllFiles && file[0] === '.') {
return false
}
if (hasExcludePattern) {
return !excludePattern.test(file)
| javascript | {
"resource": ""
} |
q1296 | generatePKP | train | function generatePKP (privateKey, dicPopl, idProvoz, idPokl, poradCis, datTrzby, celkTrzba) {
const options = [dicPopl, idProvoz, idPokl, poradCis, datTrzby, celkTrzba]
const strToHash = options.join('|') | javascript | {
"resource": ""
} |
q1297 | generateBKP | train | function generateBKP (pkp) {
const buffer = new Buffer(pkp, 'base64')
const hash = crypto.createHash('sha1') | javascript | {
"resource": ""
} |
q1298 | doRequest | train | function doRequest (options, items) {
const uid = options.uid || uuid.v4()
const date = options.currentDate || new Date()
const soapOptions = {}
if (options.playground) {
soapOptions.endpoint = PG_WSDL_URL
}
if (options.httpClient) {
soapOptions.httpClient = options.httpClient
}
const timeout = options.timeout || 2000
const offline = options.offline || false
return new Promise((resolve, reject) => {
const body = getBodyItems(options.privateKey, date, uid, items)
soap.createClient(WSDL, soapOptions, (err, client) => {
if (err) return reject(err)
client.setSecurity(new WSSecurity(options.privateKey, options.certificate, uid))
client.OdeslaniTrzby(body, (err, response) => {
if (err) return reject(err)
try {
| javascript | {
"resource": ""
} |
q1299 | getBodyItems | train | function getBodyItems (privateKey, currentDate, uid, items) {
return {
Hlavicka: getHeaderItems(uid, | javascript | {
"resource": ""
} |